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.

Access Pattern
LIFO
Access Point
Top Only
Core Operations
Push, Pop, Peek
Typical Cost
O(1)

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, and isEmpty.

Time Cost

Push, pop, and peek are typically 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 depending on implementation.

The key rule to remember: only the top is directly accessible. You cannot remove the middle item directly in the stack model.

Why It’s Important

Undo / Redo

Actions are pushed as you work; undo pops the most recent action first.

Browser History

Back navigation behaves like a stack: the most recent page returns first.

Function Calls

The call stack stores return addresses, parameters, and local variables while functions run.

DFS Reasoning

DFS backtracking naturally matches stack behavior, whether through recursion or an explicit stack.

Visualization

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.

Common Mistakes

Confusing Queue vs Stack

A stack removes the most recent item first. A queue removes the oldest item first.

Popping an Empty Stack

Always check isEmpty() first, or handle underflow safely in your implementation.

Trying to Remove the Middle

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.