public class IntegerStack { private int[] stack; private int capacity; private int size; public IntegerStack(int initialCapacity) { stack = new int[initialCapacity]; capacity = initialCapacity; size = 0; } private void doubleCapacity() { int[] newStack = new int[2*capacity]; for (int i = 0; i < capacity; i++) newStack[i] = stack[i]; capacity = 2*capacity; stack = newStack; } /** Pushes item onto the stack */ public void push(int item) { if (isFull()) doubleCapacity(); stack[size++] = item; } /** Pops off an item from the stack */ public int pop() { if (isEmpty()) throw new RuntimeException("Trying to pop an empty stack."); return stack[--size]; } /** Returns the item at the top of the stack */ public int top() { if (isEmpty()) throw new RuntimeException("Trying to access an empty stack."); return stack[size-1]; } /** Returns true iff the stack is empty. */ public boolean isEmpty() { return size == 0; } /* Returns true iff the stack is full. */ private boolean isFull() { return size == capacity; } /** Returns a string representation of the stack. */ public String toString() { String s = ""; for (int i = size - 1; i >= 0; i--) s += stack[i] + " "; return s; } public static void main(String[] args) { int capacity = 10; IntegerStack is = new IntegerStack(capacity); // int n = is.pop(); this should cause an exception // int n = is.top(); this should cause an exception if (is.isEmpty()) System.out.println("stack is empty"); else System.out.println("stack is not empty"); for (int i = 0; i < capacity; i++) is.push(i); is.push(capacity); System.out.println("stack before popping: " + is); System.out.println(is.pop()); System.out.println("stack after popping: " + is); System.out.println("top of stack is: " + is.top()); } }