CS205

Stack

LIFO (Last-In, First-Out) data structure

Interactive Stack Operations

Drag elements onto the stack to push, or click the top element to pop.

Drag elements to push onto stack
1
2
3
4
5
6
7
8
9
Stack (LIFO)Size: 0 / 8

Stack is empty

Drag an element here to push

Operation History

No operations yet

Java Implementation

Array-Based Stack

Stack implementation using an array with a top pointer

public class ArrayStack<T> {
    private T[] array;
    private int top;
    private int capacity;

    @SuppressWarnings("unchecked")
    public ArrayStack(int capacity) {
        this.capacity = capacity;
        this.array = (T[]) new Object[capacity];
        this.top = -1;
    }

    public void push(T item) {
        if (top >= capacity - 1) {
            throw new StackOverflowError("Stack is full");
        }
        array[++top] = item;
    }

    public T pop() {
        if (isEmpty()) {
            throw new EmptyStackException();
        }
        return array[top--];
    }

    public T peek() {
        if (isEmpty()) {
            throw new EmptyStackException();
        }
        return array[top];
    }

    public boolean isEmpty() {
        return top == -1;
    }

    public int size() {
        return top + 1;
    }
}
Time: O(1) for all operationsSpace: O(n) where n is capacity
Implementation Comparison
AspectArray-BasedLinkedList-Based
MemoryFixed size, may waste space if not fullDynamic, uses only what's needed + node overhead
Push/PopO(1) - simple index updateO(1) - pointer update
OverflowCan overflow if array is fullNo overflow (until memory exhausted)
CacheBetter cache localityPoor cache locality
Use caseKnown max size, performance criticalUnknown size, flexibility needed

Application: Balanced Parentheses

One of the most common uses of stacks is checking if brackets are balanced. Watch how the stack helps match opening and closing brackets.

Balanced Parentheses Checker
Try:

Common Pitfalls

⚠️ Popping from Empty Stack

Calling pop() without checking if stack is empty

Stack<Integer> stack = new Stack<>();
// stack.pop(); // Throws EmptyStackException!

// Correct way:
if (!stack.isEmpty()) {
    int value = stack.pop();
}

Prevention: Always check isEmpty() before pop() or peek()

⚠️ Stack Overflow

Pushing to a full fixed-size stack

// With fixed-size array implementation
ArrayStack stack = new ArrayStack(3);
stack.push(1);
stack.push(2);
stack.push(3);
// stack.push(4); // StackOverflowError!

Prevention: Check size before push, or use dynamic implementation

⚠️ Using Stack When Queue Needed

Using LIFO when FIFO is required

// Wrong: Using stack for BFS
Stack<Node> stack = new Stack<>(); // LIFO!

// Correct: Use queue for BFS
Queue<Node> queue = new LinkedList<>(); // FIFO

Prevention: Think about order: reverse order → Stack, arrival order → Queue