/** * This class implements a generic Stack using dynamic array. */ public class Stack { int capacity; int size; T[] istack; /** * Creates a new stack of T with capacity cap. */ public Stack(int cap) { capacity = cap; size = 0; istack = (T[]) new Object[cap]; } private static int DEFAULT_CAPACITY = 10; public Stack() { this(DEFAULT_CAPACITY); } /** * Doubles the capacity of the array. */ private void resize() { capacity *= 2; T[] newStack = (T[]) new Object[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(T 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 T 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 T pop() { if (isEmpty()) throw new RuntimeException("Trying to pop an empty stack."); return istack[--size]; } /** * @return true if and only 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.toString(); } public static void main(String[] args) { Stack is1 = new Stack(5); Stack is2 = new Stack(); 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()); } }