Learn › Stacks & queues

Stacks (LIFO)

Push and pop from one end — the structure behind undo, parsing, and the call stack. · 5 min read

A stack only lets you touch one end, the top. You push to add and pop to remove, so the last item in is the first out — LIFO. Think of a stack of plates.

Interactive visualization: Push / pop — step through it frame by frame on this page.

The stack invariant

One end, one update
  1. only the top is visible — Push and pop never touch the middle.
  2. push writes one new top — Constant pointer/index update.
  3. pop removes one top — Constant pointer/index update.

Result: O(1) push/pop

Previous: Stacks & queues from a list · Next: Queues (FIFO)

More in Stacks & queues