Lessons · #3 of 11

Stacks

LIFO — newest in, newest out

Stack · LIFO

size0 top
empty stack — push to begin
init

Mini-game · balanced brackets (powered by a stack)

Type an expression. Brackets must open and close in mirror order({[…]}) is fine, ([)] is not. The parser uses a stack: every opener pushes the expected closer; every closer must match the value on top. Watch how each character is classified, and how the stack grows and shrinks below.

try
  • opener → push
  • closer matches top
  • mismatch / underflow
  • ignored char

Try it: Push tokens onto the tower; pop them off. Then below: feed any bracketed string into the parens game — the stack is the parser.

Why it matters

Stacks are everywhere: function calls, undo/redo, expression parsing, backtracking algorithms. Understanding stacks means understanding how programs execute and how to solve problems that require 'remembering' and 'undoing'.

The idea

Think of a stack of plates in a cafeteria. You can only add or remove from the top. The last plate placed is the first one taken.

Last In, First Out (LIFO).

This simple constraint is incredibly powerful:

All operations are O(1) - you only ever touch the top.

Key takeaways

Going deeper

The call stack is why recursive functions work — each call's local variables are pushed onto the stack and popped when returning. Stack overflow happens when recursion goes too deep. Stacks are also key to converting infix to postfix notation (shunting-yard algorithm) and evaluating postfix expressions in a single pass.

In the wild

Math details

Time Complexity
Push: O(1)
Pop: O(1)
Peek: O(1)
Search: O(n)
Space
O(n) for n elements

Implementation

Stack Operations

let mut stack = Vec::new();

stack.push(1);  // Push onto top
stack.push(2);
stack.push(3);  // Stack: [1, 2, 3] (3 is top)

let top = stack.pop();  // Returns Some(3)
let peek = stack.last(); // Returns Some(&2)

Classic Applications

Practice

Three classic stack problems — each one is a different way of using the LIFO discipline:

Browse all practice problems