public class Stack { private int count;//element number in stack private int top;//top element private int MAXSIZE = 10;//capacity private int space [];//array public Stack() { space = new int[MAXSIZE]; count = 0; top = -1; } //inspectors public boolean isEmpty() { return (count <= 0); } public int getSize() { return count; } public int stackTop() { return top; } public boolean equals(Stack s) { if(count == s.count) return false; for(int i = 0; i < count; i++) if(space[i] != s.space[i]) return false; return true; } public String toString() { String str = "["; for(int i = 0; i < count; i++) str = str + " "+space[i]; str = str + "]"; return str; } //Modifiers /*public void push(int e) { space[count] = e; top = e; count++; }*/ public void push(int e) { if(count == MAXSIZE) { int [] space2 = new int[MAXSIZE*2]; for(int i = 0; i < count; i++) space2[i] = space[i]; MAXSIZE = MAXSIZE*2; space = space2; } space[count] = e; top = e; count++; } public boolean pop() { if(count <= 0) return false; count--; if(count == 0) top = -1; else top = space[count-1]; return true; } public Stack copyStack() { Stack cp = new Stack(); if(isEmpty()) return cp; for(int i = 0; i < count; i++) cp.push(space[i]); return cp; } }
public class StackTest { public static void main(String args[]) { Stack s = new Stack(); for(int i = 0; i < 11; i++) s.push(i); System.out.println(s); while(!s.isEmpty()) { s.pop(); System.out.println(s); } } }