Data Structures · Stack

Stack

Think of a stack of plates by the sink. You add a clean plate to the top, and when you need one, you take it off the top too. The last plate you put down is the first one you pick up. A stack is that rule turned into a data structure — add and remove from one end only. It sounds almost too simple, but that one rule is exactly what powers the undo button and the browser back arrow.

What is it

A stack is a pile where you only ever touch the top. You add to the top, and you remove from the top — never the middle, never the bottom. This one-end-only rule has a name: LIFO, last in, first out. The last thing you added is always the first thing to leave.

How it works

The stack remembers one spot: the top. Adding an item, called a push, drops it onto the top and moves the marker up. Removing an item, called a pop, takes the top item and moves the marker down. Because you only ever work at the top, both moves are one quick step — no shuffling, no searching. The middle of the pile is off-limits by design, and that limit is what keeps a stack fast and predictable.

Operations

Name Big-O Why
Push (add to top) O(1) drop it on top, move the marker up, done
Pop (remove top) O(1) take the top item, move the marker down
Peek (look at top) O(1) read the top without removing it
Is it empty? O(1) just check whether the marker is at the bottom
Search inside O(n) you'd have to pop through the pile to find a buried item

When to use

Reach for a stack whenever the newest thing should be handled first. Undo history: the last action you did is the first to reverse. The back button: the last page you visited is the first to return to. It also runs behind the scenes every time a program calls a function, remembering where to return. When you hear 'go back to the most recent one,' think stack.

Watch out for

The catch is the rule itself: you can only reach the top. Need the item at the bottom? You have to remove everything above it first. A stack is the wrong tool when you need to peek in the middle or handle things in the order they arrived — that is a queue's job. Also, a fixed-size stack can overflow if you push more than it can hold, which is where the phrase 'stack overflow' comes from.

Analogy

A stack of plates by the sink. You add to the top and take from the top. The last plate down is the first plate up — and the plate at the bottom waits until every plate above it is gone.

Practice lessons

Lessons coming soon.