Lesson 13 · Linear structures

Stacks

A stack is a Last-In-First-Out (LIFO) structure: items go on and come off at the same end, the top. Push, pop and peek are all O(1). That one rule is enough to match brackets, evaluate expressions and run every function call in a program.

Stacks concept diagramA visual explanation of the layout and operations shown in this lesson.push and pop both act on the top of the pileCBAtoppush / pop hereoldest element, reached lastlast in, first out
1

One End, Four Operations

A stack is a linear structure with a single point of access. Items are added and removed at the same end, called the top, so the item added last is always the first one out: Last In, First Out (LIFO). A pile of plates works the same way.

Four stack operations define it. push places a value on the top. pop removes and returns the top value. peek (or top) reads the top without removing it. isEmpty reports whether anything is left. All four are O(1), because each touches one end and never looks at the rest.

Two errors have names. Underflow is a pop or peek on an empty stack; it must throw or return a clear signal, never hand back whatever memory happens to be there. Overflow is a push onto a fixed-size stack that is full. A growable stack cannot overflow, but a fixed array and the call stack can.

What makes it a stack is what it leaves out: no indexing, no search, no access to the middle. That limit is the value. Code that receives a stack knows the order things will come back in.

  • Stack vs queue: both add at one end, but a stack removes from the same end and a queue from the other
  • A fixed-array stack of capacity n is full when top == n; check before writing
  • Python's list, C++'s std::stack and Java's ArrayDeque all give the four operations in O(1) (push is amortised O(1))
2

Array or Linked List

An array-backed stack keeps the items next to each other and an integer top marking the next free slot. Push writes at top and adds 1; pop subtracts 1 and reads. Because the items sit together in memory, the CPU cache works well, and this is usually the faster choice.

Its one complication is capacity. When the array fills, a larger one is allocated and everything is copied across, an O(n) step. Because the capacity doubles (or grows by a fixed factor), these copies get rarer as fast as they get bigger, so the average cost per push stays constant: push is amortised O(1), not worst-case O(1). One unlucky push can still cost O(n), which matters in real-time code. See amortized analysis for the counting.

A stack built from linked list nodes pushes by allocating a node and linking it in at the head, and pops by moving the head to the next node. There is no capacity and no resize, so every operation is strictly O(1). The costs are a pointer per item, an allocation per push and nodes scattered across memory.

Choose the array unless you need the worst-case guarantee or cannot allocate one large block. In practice: Python's list is the usual stack (append and pop); C++'s std::stack is an adapter over std::deque by default and can sit on a std::vector instead; Java's old Stack class is synchronised and inherits from Vector, so ArrayDeque is the recommended replacement.

The two backings, and what each costs
Array-backedLinked-list-backed
PushAmortised O(1)Strict O(1)
Pop, peekO(1)O(1)
Worst-case pushO(n) on resizeO(1)
Memory per elementValue onlyValue + pointer + allocation header
LocalityContiguous, prefetchedScattered, cache misses
CapacityGrows by reallocationUnbounded
3

Evaluating Expressions

The best-known applications of stack are bracket matching (the tracer below), expression evaluation, undo history and the call stack. Expressions show the idea most clearly.

Arithmetic as people write it, infix such as 3 + 4 × 2, is awkward for a machine: precedence and parentheses mean the operators cannot simply be applied left to right. In postfix (reverse Polish notation) the same expression is 3 4 2 × +. It needs no parentheses and no precedence rules when it is evaluated.

Dijkstra's shunting-yard algorithm converts infix to postfix with an operator stack. Operands go straight to the output. An operator first pops any stacked operators of higher or equal precedence to the output, then is pushed itself. A closing parenthesis pops back to its matching opener. The stack holds operators whose operands are not complete yet.

Evaluating the postfix needs a second stack, this one of numbers. Push each number; on an operator, pop two values, apply it, and push the result. When the input ends, one value is left, and it is the answer. For 5 1 2 + 4 × + 3 −: 1 + 2 = 3, 3 × 4 = 12, 5 + 12 = 17, 17 − 3 = 14.

Order matters for − and ÷. The first value popped is the right operand, so compute second_popped OP first_popped. Swapping them still gives the right answer for + and ×, which is why the bug survives casual testing.

This is close to how interpreters and calculators work. The JVM and CPython both run their bytecode on an operand stack in exactly this way.

Key reference

Terms, operations, and practical uses

Core operations

  • PushAdding an item to the top of the stack. O(1), amortised O(1) when the array has to grow.
  • PopRemoving and returning the item at the top. O(1). On an empty stack it is an underflow.
  • Peek / TopLooking at the element on the top of the stack without removing it.

Implementation details

  • Array BackingA dynamic array and an integer top index. Cache-friendly, but a push that triggers a resize costs O(n).
  • Linked List BackingPush and pop at the head node. No resizing, but one allocation per push and scattered memory.
  • Stack OverflowAn error that occurs when a stack exceeds its allocated memory limit, most famously caused by infinite recursion.

Practical applications

  • Call StackThe internal structure used by the OS and runtime to track active function calls, local variables, and return addresses.
  • Expression ParsingChecking that brackets, or XML and HTML tags, open and close in the right nested order.
  • Shunting-YardDijkstra's method for turning infix expressions such as 3 + 4 × 2 into postfix (3 4 2 × +) with an operator stack.
Implementation

Code in Python, C++ and Java

def is_valid(s):
    stack = []
    pairs = {')': '(', ']': '[', '}': '{'}
    for char in s:
        if char in pairs.values():
            stack.append(char)
        elif char in pairs.keys():
            if not stack or stack[-1] != pairs[char]:
                return False
            stack.pop()
    return len(stack) == 0

print('Valid:', is_valid("{[()]}"))
#include <iostream>
#include <stack>
#include <unordered_map>
using namespace std;

bool isValid(string s) {
    stack<char> st;
    unordered_map<char, char> pairs = {{')', '('}, {']', '['}, {'}', '{'}};
    for (char c : s) {
        if (c == '(' || c == '[' || c == '{') {
            st.push(c);
        } else if (pairs.count(c)) {
            if (st.empty() || st.top() != pairs[c]) return false;
            st.pop();
        }
    }
    return st.empty();
}

int main() {
    cout << "Valid: " << (isValid("{[()]}") ? "True" : "False") << endl;
    return 0;
}
import java.util.*;

class Main {
    public static boolean isValid(String s) {
        Deque<Character> stack = new ArrayDeque<>();
        Map<Character, Character> pairs = Map.of(')', '(', ']', '[', '}', '{');
        for (char c : s.toCharArray()) {
            if (c == '(' || c == '[' || c == '{') {
                stack.push(c);
            } else if (pairs.containsKey(c)) {
                if (stack.isEmpty() || stack.peek() != pairs.get(c)) return false;
                stack.pop();
            }
        }
        return stack.isEmpty();
    }
    public static void main(String[] args) {
        System.out.println("Valid: " + (isValid("{[()]}") ? "True" : "False"));
    }
}
Watch it run

Step through it

Running on "{[()]}", then "{[)]}", "())" and "{["

input { [ ( ) ] }0{1[2(3)4]5}stackemptystack empty, nothing waiting
Step 1

Six brackets and an empty stack

The scan reads the string once, left to right. An opening bracket cannot be judged when it is read, because its partner comes later, so it waits on the stack. A closing bracket is judged at once, against the top only.

Output
1 / 14
4

The Call Stack

The most important stack is the one the runtime keeps for you. Each function call pushes a stack frame holding the arguments, local variables and the return address. When the function returns, its frame is popped and execution continues at that address.

LIFO is the only order that works here, because calls nest the way brackets do. If a calls b and b calls c, then c must finish before b, and b before a. The call started last always finishes first.

This is also what makes recursion work. Each recursive call gets its own frame with its own copy of the locals, so one level cannot overwrite another. The base case stops the pushing. Without it, frames pile up until the stack's fixed memory runs out: a stack overflow. CPython stops at a recursion limit of 1,000 frames by default; a C or C++ program gets a fixed stack (commonly 8 MB on Linux, 1 MB on Windows) and crashes when it is used up.

A stack trace is a printout of these frames, innermost first: the exact chain of calls that led to the failure.

It works the other way too. Any recursive algorithm can be rewritten as a loop that manages its own stack of the state the frames were holding. That is the standard fix when the input is deep enough to overflow, and it is how iterative depth-first search and iterative tree traversals are written.

  • Undo in an editor and the browser's Back button are stacks of earlier states
  • A stack kept in sorted order answers next-greater questions in one pass: see monotonic stacks
  • Two stacks can also make a queue: implement queue using stacks