public class Stack {
    private int sp;
    private int[] arr;
    // Konstruktoren:
    public Stack() {
        sp  = -1; 
        arr = new int[4];
    }
    // Objekt-Methoden:
    public boolean isEmpty() {
        return sp < 0;
    }

    //    public int pop() {
    //        return arr[sp--];
    //    }    
    public int pop() {
        int result = arr[sp];
        if (sp == arr.length/4 && sp >= 2) {
            int[] b = new int[2*sp];
            for(int i = 0; i < sp; ++i)
                b[i] = arr[i];
            arr = b;
        }
        sp--;
        return result;
    }

    public void push(int x) {
        ++sp;
        if (sp == arr.length) {
            int[] b = new int[2*sp];
            for (int i = 0; i < sp; ++i) b[i] = arr[i];
            arr = b;
        }
        arr[sp] = x;
    }
    public String toString() {
        if (sp == -1) return "[]";
        String res = "[" + arr[0];
        for (int i=1; i<=sp; ++i) {
            res += ", " + arr[i];
        }
        res += "]";
        return res;
    }
    public static void main(String args[]) {
        Stack st = new Stack();

        st.push(1);
        st.push(2);
        st.push(3);
        st.push(4);
        System.out.println(""+st);
        while (st.isEmpty() == false) {
            int x = st.pop();
            System.out.println(x);
        }
    }
} // end of class Stack


