Maggie HTTN
Data Structures • Beginner Foundation

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

Access pattern
LIFO (Last In, First Out)
Where operations happen
Only at the top of the stack
Common operations
push, pop, peek/top, isEmpty
Time cost (typical)
push/pop/peek are O(1)

Beginner Rules

  1. Push: add a new item on top.
  2. Pop: remove the top item (and return it).
  3. Peek / Top: look at the top item without removing it.
  4. Underflow: popping from an empty stack is an error (or returns nothing).
  5. Only the top is visible: you can’t remove the middle directly.

Why It’s Important

Undo / Redo
Actions are pushed as you work; undo pops the most recent action.
Browser history
Back navigation behaves like a stack: most recent page returns first.
Function calls
The call stack stores return addresses and local variables.
DFS reasoning
DFS backtracking matches stack behavior (explicit stack or recursion).

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.