/** * This class implements an Integer Stack using dynamic array. */ public class IntegerStack { int capacity; int size; int[] istack; /** * Creates a new integer stack with capacity cap. */ public IntegerStack(int cap) { capacity = cap; size = 0; istack = new int[cap]; } private static int DEFAULT_CAPACITY = 10; public IntegerStack() { this(DEFAULT_CAPACITY); } /** * Doubles the capacity of the array. */ private void resize() { capacity *= 2; int[] newStack = new int[capacity]; for (int i = 0; i < size; i++) newStack[i] = istack[i]; istack = newStack; } /** * Pushes item onto the stack. * @param item the item to be inserted into the stack */ public void push(int item) { if (isFull()) resize(); istack[size++] = item; } /** * Returns the topmost item on the stack without disturbing it. * @return the topmost item on the stack */ public int top() { if (isEmpty()) throw new RuntimeException("Trying to access an empty stack."); return istack[size-1]; } /** * Pops off the topmost item on the stack and returns it. * @return the item on top of the stack */ public int pop() { if (isEmpty()) throw new RuntimeException("Trying to pop an empty stack."); return istack[--size]; } /** * @return true if and only if the stack is empty */ public boolean isEmpty() { return size == 0; } /** * @return true if and only if the stack is full */ public boolean isFull() { return size == capacity; } /** * @return a string representation of the stack */ public String toString() { if (isEmpty()) return "EMPTY STACK"; StringBuffer sb = new StringBuffer(); for (int i = size-1; i >= 0; i--) sb.append(" " + istack[i]); return sb + ""; } public static void main(String[] args) { IntegerStack is1 = new IntegerStack(5); IntegerStack is2 = new IntegerStack(); // is1.pop(); // This line wiil throw an exception System.out.println("is1 = " + is1); System.out.println("is2 = " + is2); for (int i = 0; i < 20; i++) { is1.push(i); is2.push(2*i); } System.out.println("is1 = " + is1); System.out.println("is2 = " + is2); System.out.println("top(is1) = " + is1.top()); } }