package DataStructures; import java.util.NoSuchElementException; /** * An array implementation of a stack * @param the type of elements held in this stack * @author Peter Williams */ public class StackArray implements Stack { private E[] stack; private int top; // for storing next item /** * Creates an empty stack suitable for holding items of type E */ public StackArray() { stack = (E[])new Object[1]; top = 0; } public boolean isEmpty() { return top == 0; } public void push(E item) { if (top == stack.length) { // expand the stack E[] newStack = (E[])new Object[2*stack.length]; System.arraycopy(stack, 0, newStack, 0, stack.length); stack = newStack; } stack[top++] = item; } public E pop() { if (top == 0) { throw new NoSuchElementException(); } else { return stack[--top]; } } }