TExcelTAD

Stacks

A stack is a collection where the last item added is the first one removed: LIFO (last in, first out). Think of a stack of plates: you put plates on top and take them from the top. You never pull one out of the middle.

Operations

Operation Meaning Cost
push(x) put x on top O(1)
pop() remove and return the top item O(1)
peek() look at the top item without removing it O(1)
is_empty() is the stack empty? O(1)
size() number of items O(1)

Popping from an empty stack is an error called underflow.

A stack on top of a Python list

A Python list is a perfect stack if you only use its end: append and pop() are both O(1).

python · try it yourself
class Stack:
    def __init__(self):
        self._items = []

    def push(self, item):
        self._items.append(item)

    def pop(self):
        if not self._items:
            raise IndexError("pop from an empty stack")
        return self._items.pop()

    def peek(self):
        if not self._items:
            raise IndexError("peek at an empty stack")
        return self._items[-1]

    def is_empty(self):
        return not self._items

    def __len__(self):
        return len(self._items)

s = Stack()
for item in "ABC":
    s.push(item)
print("peek:", s.peek())
print("pop:", s.pop())
s.push("D")
print("pop:", s.pop(), "pop:", s.pop(), "pop:", s.pop())
try:
    s.pop()
except IndexError as err:
    print("error:", err)
peek: C
pop: C
pop: D pop: B pop: A
error: pop from an empty stack

This is exactly the sequence from the animation: C is popped first, then D, B, A, and the last pop underflows.

Note: Don't use list.pop(0) / insert(0, x) for a stack's top: those shift every element and are O(n). Always work at the end of the list.

A stack as a linked list

The head of a linked list also works as the top of a stack, since adding and removing at the head is O(1):

python · try it yourself
class Node:
    def __init__(self, value, next=None):
        self.value = value
        self.next = next

class LinkedStack:
    def __init__(self):
        self.top = None
        self.size = 0

    def push(self, value):
        self.top = Node(value, self.top)
        self.size += 1

    def pop(self):
        if self.top is None:
            raise IndexError("pop from an empty stack")
        value = self.top.value
        self.top = self.top.next
        self.size -= 1
        return value

s = LinkedStack()
for n in [1, 2, 3]:
    s.push(n)
print(s.pop(), s.pop(), s.size)
3 2 1

Application: balanced brackets

Compilers and editors check whether brackets match with a stack: push every opening bracket, and when a closing bracket arrives, the top of the stack must be its partner.

python · try it yourself
PAIRS = {")": "(", "]": "[", "}": "{"}

def balanced(text):
    stack = []
    for ch in text:
        if ch in "([{":
            stack.append(ch)
        elif ch in PAIRS:
            if not stack or stack.pop() != PAIRS[ch]:
                return False
    return not stack            # leftovers mean an unclosed bracket

for expr in ["(a[0] + b) * {c}", "([)]", "((x)", "f(g(h()))"]:
    print(f"{expr:<18} {balanced(expr)}")
(a[0] + b) * {c}   True
([)]               False
((x)               False
f(g(h()))          True

Application: evaluating postfix expressions

In postfix (Reverse Polish) notation the operator comes after its operands: 3 4 + 2 * means (3 + 4) * 2. A stack evaluates it in one pass with no parentheses or precedence rules:

python · try it yourself
def eval_postfix(expr):
    stack = []
    for token in expr.split():
        if token in "+-*/":
            right = stack.pop()
            left = stack.pop()
            if token == "+": stack.append(left + right)
            elif token == "-": stack.append(left - right)
            elif token == "*": stack.append(left * right)
            else: stack.append(left / right)
        else:
            stack.append(float(token))
        print(f"{token:>2}  stack: {stack}")
    return stack.pop()

print("result:", eval_postfix("3 4 + 2 * 7 -"))
 3  stack: [3.0]
 4  stack: [3.0, 4.0]
 +  stack: [7.0]
 2  stack: [7.0, 2.0]
 *  stack: [14.0]
 7  stack: [14.0, 7.0]
 -  stack: [7.0]
result: 7.0

Where stacks appear

  • The call stack: every function call pushes a frame; return pops it. Infinite recursion overflows it (RecursionError in Python).
  • Undo in editors: each action is pushed; undo pops the latest.
  • Depth-first search and backtracking (Graph Traversal, Recursion & Backtracking lessons).
  • Browser back button: visited pages form a stack.

Test yourself

You push 1, 2, 3 onto an empty stack and then pop twice. What is on top?

  1. 1
  2. 2
  3. 3
  4. The stack is empty

Which Python list operations make an O(1) stack?

  1. insert(0, x) and pop(0)
  2. append(x) and pop()
  3. append(x) and pop(0)
  4. sort() and pop()

What is the value of the postfix expression 5 1 2 + 4 * + 3 -?

  1. 14
  2. 18
  3. 12
  4. 20