Stack (Abstract Data Type)
A stack stores items using LIFO — Last In, First Out. The only access point is the top.
Stacks are one of the most important foundations in computer science. They appear everywhere: function calls (call stack), undo/redo, browser history, expression evaluation, and even algorithms like DFS.
This page teaches the stack mental model and the 3 core operations: push, pop, and peek.
Quick Facts
LIFO — Last In, First Out.
Only at the top of the stack.
Push, pop, peek/top, and isEmpty.
Push, pop, and peek are typically O(1).
Beginner Rules
Add a new item on top.
Remove the top item and return it.
Look at the top item without removing it.
Popping from an empty stack is an error, or returns nothing depending on implementation.
Why It’s Important
Actions are pushed as you work; undo pops the most recent action first.
Back navigation behaves like a stack: the most recent page returns first.
The call stack stores return addresses, parameters, and local variables while functions run.
DFS backtracking naturally matches stack behavior, whether through recursion or an explicit stack.
Visualization
This demo visualizes push, pop, and peek using a clear top-of-stack highlight. Watch how the most recently added item is always the first one removed.
Common Mistakes
A stack removes the most recent item first. A queue removes the oldest item first.
Always check isEmpty() first, or handle underflow safely in your implementation.
Stacks are designed for top-only access. Middle removal breaks the abstraction.
Outcome
After this lesson, learners should be able to describe LIFO, correctly apply push, pop, and peek, and recognize stacks in real applications like undo/redo, browser history, recursion, and DFS.