Untitled

 avatar
unknown
java
2 years ago
810 B
7
Indexable
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");
        }
    }
}
Editor is loading...
Leave a Comment