Stack Operations
Push, pop, and peek a live LIFO stack. Includes capacity handling and underflow feedback.
Push, pop, and peek a live LIFO stack. Includes capacity handling and underflow feedback.
op 1 / 1
What's happening
A stack starts empty (or pre-filled). All action happens at the TOP, push adds there, pop removes from there. Capacity: 8.
Push, pop, and peek are all O(1), they only touch the top. The Back/Forward buttons scrub through your operation history, so you can re-examine each state change.
Understand the algorithm
What it is
A stack is a LIFO (last-in, first-out) collection: push adds to the top, pop removes from the top, peek reads the top without removing.
Why it matters
LIFO is the structure of 'undo' and of postponed work. Function calls, expression evaluation, backtracking, and browser history all rely on it. Feeling why you can only touch the top, and what that costs, makes later topics like recursion and DFS click.
How it works
- 1push(value): place the value on top, O(1).
- 2peek(): read the top element without removing it, O(1).
- 3pop(): remove and return the top, O(1). Underflow (pop on empty) is an error to handle.
- 4Everything below the top is untouchable until the elements above it are popped.
Real-world uses
- The call stack that runs every function in every program
- Undo/redo in editors
- Balanced-bracket checking and expression evaluation
- Depth-first search and backtracking algorithms
Strengths
- All operations O(1)
- Trivial to build on an array or linked list
- The natural structure for nested or deferred work
Limitations
- No random access, reaching the bottom means popping everything above
- Unbounded growth needs capacity management (or a dynamic array under the hood)
- Wrong structure whenever 'oldest first' matters, that is a queue