← Lessons

quiz vs the machine

Silver1020

Algorithms

The Stack Abstract Data Type

A last in, first out collection that powers undo, recursion, and parsing.

4 min read · intro · beat Silver to climb

A collection with discipline

A stack is an abstract data type defined by its rules, not its storage. It allows access only at one end, called the top. You can push a value onto the top, pop the top value off, and peek at the top without removing it. The defining behavior is last in, first out: the most recently added item is the first to leave.

Why the restriction is useful

Limiting access sounds weak, but it models many real processes precisely.

  • Function calls nest, so a call stack pops the deepest call first.
  • An undo feature reverses the most recent action first.
  • Matching brackets in code is checked by pushing openers and popping on closers.

How it is built

A stack is an interface that can sit on different storage. A dynamic array works well, pushing and popping at its end. A linked list works too, treating the head as the top. Both give constant time push and pop, so the choice rarely matters to the user of the stack.

Key idea

A stack is a last in, first out collection exposing push, pop, and peek, ideal for nested processes like recursion, undo, and bracket matching, and it can be backed by an array or a linked list.

Check yourself

Answer to earn rating on the learn ladder.

1. Which ordering does a stack follow?

2. Which problem is naturally solved with a stack?