import java.util.*;
public class DynamicArrayStack<E> implements Stack<E> {
    private int limit;		// maximal number of elements
    private E[] data;		// elements of the list
    private int num = 0;	// current number of elements
    public DynamicArrayStack(int limit) {
        this.limit = limit;
        this.data = (E[]) new Object[limit];
    }
    public void push(E elem) {
        if (this.num >= this.limit) {
            E[] newData = (E[]) new Object[2*this.limit];
            for (int j = 0; j < limit; j++) {
                newData[j] = data[j];
            }
            this.data = newData;
            this.limit *= 2;
        }
        this.data[num] = elem;
        num++;
    }
    public E pop() {
        E result = this.peek();
        num--;
        return result;
    }
    public E peek() {
        if (this.isEmpty()) {  throw new RuntimeException("empty stack");  }
        return this.data[this.num-1];
    }
    public boolean isEmpty() {
        return this.num == 0;
    }
    public static void main(String[] args) {
        Stack<Integer> stack = new DynamicArrayStack<Integer>(2);
        for (int i = 0; i < 100; i++) {
            stack.push(i*i);
        }
        while (!stack.isEmpty()) {
            System.out.println(stack.pop());
        }
    }
}

