01: /*************************************************************************
02: * *
03: * 1) This source code file, in unmodified form, and compiled classes *
04: * derived from it can be used and distributed without restriction, *
05: * including for commercial use. (Attribution is not required *
06: * but is appreciated.) *
07: * *
08: * 2) Modified versions of this file can be made and distributed *
09: * provided: the modified versions are put into a Java package *
10: * different from the original package, edu.hws; modified *
11: * versions are distributed under the same terms as the original; *
12: * and the modifications are documented in comments. (Modification *
13: * here does not include simply making subclasses that belong to *
14: * a package other than edu.hws, which can be done without any *
15: * restriction.) *
16: * *
17: * David J. Eck *
18: * Department of Mathematics and Computer Science *
19: * Hobart and William Smith Colleges *
20: * Geneva, New York 14456, USA *
21: * Email: eck@hws.edu WWW: http://math.hws.edu/eck/ *
22: * *
23: *************************************************************************/package edu.hws.jcm.data;
24:
25: /**
26: * A standard stack of values of type double, which can grow to arbitrary size.
27: */
28: public class StackOfDouble implements java.io.Serializable {
29:
30: private double[] data; // Contents of stack.
31: private int top; // Number of items on stack.
32:
33: /**
34: * Create an initially empty stack. It initially has space allocated for one item.
35: */
36: public StackOfDouble() {
37: data = new double[1];
38: }
39:
40: /**
41: * Create an empty stack that initially has space for initialSize items pre-allocated.
42: * If initialSize <= 0, an initialSize of 1 is used.
43: */
44: public StackOfDouble(int initialSize) {
45: data = new double[initialSize > 0 ? initialSize : 1];
46: }
47:
48: /**
49: * Add x to top of stack.
50: */
51: public void push(double x) {
52: if (top >= data.length) {
53: double[] temp = new double[2 * data.length];
54: System.arraycopy(data, 0, temp, 0, data.length);
55: data = temp;
56: }
57: data[top++] = x;
58: }
59:
60: /**
61: * Remove and return the top item on the stack.
62: * Will throw an exception of type java.util.EmptyStackException
63: * if the stack is empty when pop() is called.
64: */
65: public double pop() {
66: if (top == 0)
67: throw new java.util.EmptyStackException();
68: return data[--top];
69: }
70:
71: /**
72: * Return true if and only if the stack contains no items.
73: */
74: public boolean isEmpty() {
75: return (top == 0);
76: }
77:
78: /**
79: * Clear all items from the stack.
80: */
81: public void makeEmpty() {
82: top = 0;
83: }
84:
85: /**
86: * Return the number of items on the stack.
87: */
88: public int size() {
89: return top;
90: }
91:
92: } // end class StackOfDouble
|