Untitled

mail@pastecode.io avatar
unknown
java
7 months ago
810 B
4
Indexable
Never
class Stack<T> {

    T[] list;
    int tos;

    Stack() {
        tos = -1;
        this.list = (T[]) new Object[10];
    }

    void push(T item) {
        if (tos == list.length - 1) {
            // Stack is full, need to resize
            int newSize = list.length * 2;
            list = Arrays.copyOf(list, newSize);
            System.out.println("Resized: " + Arrays.toString(list));
        }

        list[++tos] = item;
        System.out.println("Pushed " + item + ": " + Arrays.toString(list));
    }

    void pop() {
        if (tos > -1) {
            int newSize = tos;
            tos--;
            list = Arrays.copyOf(list, newSize);
            System.out.println("Popped: " + Arrays.toString(list));
        } else {
            System.out.println("Stack is empty");
        }
    }
}
Leave a Comment