Stack (Abstract Data Type)
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
Beginner Rules
- Push: add a new item on top.
- Pop: remove the top item (and return it).
- Peek / Top: look at the top item without removing it.
- Underflow: popping from an empty stack is an error (or returns nothing).
- Only the top is visible: you can’t remove the middle directly.
Why It’s Important
Demo / Media
Animation
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 (LIFO).
Common Mistakes (and how to avoid them)
- Confusing queue vs stack: stack removes the most recent; queue removes the oldest.
- Popping empty stack: always check
isEmpty()first (or handle underflow). - Trying to “remove the middle”: stacks are designed for top-only access.
Outcome
Learners can describe LIFO, correctly apply push/pop/peek, and recognize stacks in real applications like undo/redo, browser history, recursion, and DFS.