Stack
1if top == capacity − 1: overflow (the stack is full)2top ← top + 13a[top] ← v
What is a Stack?
A stack is a collection where you can only add or remove items at one end, called the top. Like a pile of plates, the item you put on last is the first one you take off. This rule is called LIFO: last in, first out.
The visualizer stores the stack in a fixed-size array. A single number, top, remembers where the top item is. Pushing moves it up one slot and writes the value; popping reads the value and moves it down. Nothing else ever moves, which is why every operation is instant.
Only the top can be seen, added to, or removed.
How the Operations Work
Push
Check there is room (top < capacity − 1), move top up by one and store the value there. Pushing onto a full stack is a stack overflow.
Pop
Check the stack isn't empty (top ≠ −1), read a[top], then move top down. Popping an empty stack is a stack underflow.
Peek
Look at the top value without removing it.
Checking brackets
Push every opening bracket. Each closing bracket must match the one on top, which is popped. If everything matched and the stack ends empty, the brackets are balanced. Try {[()()]} and ([)] above.
Implementation
Properties & Complexity
Time Complexity
- • Push: O(1)
- • Pop: O(1)
- • Peek: O(1)
- • Search for a value: O(n)
Space & Properties
- • Space: O(n)
- • Order: LIFO
- • Array version: fixed capacity
- • Linked version: grows as needed
Where Stacks Are Used
- • Function calls: the call stack remembers where to return
- • Undo: the last change is undone first
- • Parsing: matching brackets, evaluating expressions
- • Back button: the last page visited comes back first
- • Depth-first search: explore the newest path first
Limitations
- • No random access: you can only reach the top
- • Fixed size (array): overflow when full
- • Recursion: too many nested calls overflow the call stack