Using Stacks

Understand last-in, first-out data with push and pop, and trace stacks used by real programs.

About 3 min read
  • Describe a stack as a last-in, first-out structure
  • Trace push, pop and peek operations
  • Handle stack overflow and underflow
  • Give real uses of stacks
Before you start

You can use arrays or lists, and you know that functions call other functions while a program runs.

Last in, first out

A stack is a collection where items are added and removed at the same end, called the top. Imagine a pile of plates: you put a new plate on top, and you take the top plate first. This rule is called last in, first out, or LIFO.

Definition: stack

A last-in, first-out data structure with access only at the top.

Definition: LIFO

Last in, first out: the newest item is the first to be removed.

Stack operations

Push adds an item to the top. Pop removes and returns the top item. Peek shows the top item without removing it. Pushing to a full fixed-size stack causes overflow, and popping from an empty stack causes underflow. Programs check for both.

Trace a stack

Start with an empty stack. Push 3, push 8, pop, push 5. What is on the stack?

Maths
push 3   → [3]
push 8   → [3, 8]
pop      → [3]        returns 8
push 5   → [3, 5]

Answer: The stack holds 3 and 5, with 5 on top.

Stacks are all around you

Undo features, browser back buttons and function calls all use stacks.

Exam focus
Say it like this“Pop removes the most recently added item.”
Not like this“Pop removes the first item.” — Use LIFO language.
Common mistakeTreating a stack like a queue. A queue removes the oldest item first.

Practice

Which operation adds an item to a stack?
Push.
Which item does pop remove?
The top item, which is the most recently added item.
What is stack underflow?
Trying to pop from an empty stack.
Going further
Explain how a stack can check whether brackets in an expression are balanced.
Push each opening bracket. Pop for each closing bracket and check that it matches. The brackets are balanced only if every pop matches and the stack is empty at the end.

Quick check

Stacks quick check

What does LIFO stand for?

The newest item at the top leaves before any older item below it.

After push A, push B, pop, which item is left?

B went on most recently, so pop removes B before anything else.

Which feature commonly uses a stack?

The newest change is reversed first, which matches last-in, first-out order.
Key takeaways
  • A stack is last in, first out.
  • Push adds, pop removes and peek looks at the top.
  • Overflow and underflow must be handled.
  • Undo and function calls use stacks.