Stacks
A stack is a dynamic set in which DELETE is not free to choose: it always removes the element inserted most recently. This policy is called last in, first out (LIFO). Insertion is traditionally called PUSH and deletion POP; PEEK (or TOP) reads the top element without removing it.
That one restriction is what makes a stack so cheap. There is no searching and no reordering: every operation touches only the top. The Stacks lesson in the DSA course shows the idea with examples; this lesson implements a stack on an array, proves its operations correct, and uses it for two classic algorithms.
A stack on an array
Keep the elements in , the bottom at position 0 and the most recent at position . The integer is also the number of elements.
PUSH(s, x) POP(s)
1 if s.top == s.capacity 1 if s.top == 0
2 error "overflow" 2 error "underflow"
3 s.a[s.top] = x 3 s.top = s.top - 1
4 s.top = s.top + 1 4 return s.a[s.top]Each procedure does a constant number of steps, so PUSH, POP and PEEK are . Underflow (popping an empty stack) is a bug in the caller; overflow only exists for a fixed capacity, and disappears if the array is a dynamic array, at the price of making PUSH amortized instead of worst case.
The correctness argument is one invariant: the elements of the stack, from bottom to top, are , in the order they were pushed and not yet popped. PUSH appends at the top end and POP removes from it, and both keep the invariant.
The Python class prints the stack after each operation, as in the animation, including the final underflow.
class Stack:
def __init__(self, capacity):
self.a, self.top = [None] * capacity, 0
def push(self, x):
if self.top == len(self.a):
raise OverflowError("stack overflow")
self.a[self.top] = x
self.top += 1
def pop(self):
if self.top == 0:
raise IndexError("stack underflow")
self.top -= 1
return self.a[self.top]
def peek(self):
if self.top == 0:
raise IndexError("stack underflow")
return self.a[self.top - 1]
def items(self):
return self.a[:self.top]
s = Stack(4)
for op in ["push 3", "push 8", "push 5", "pop", "peek", "push 1", "pop", "pop", "pop", "pop"]:
name, *arg = op.split()
try:
result = getattr(s, name)(*map(int, arg))
shown = "" if result is None else f" -> {result}"
print(f"{op:7}{shown:6} stack {s.items()}")
except IndexError as e:
print(f"{op:7} {e}")push 3 stack [3]
push 8 stack [3, 8]
push 5 stack [3, 8, 5]
pop -> 5 stack [3, 8]
peek -> 8 stack [3, 8]
push 1 stack [3, 8, 1]
pop -> 1 stack [3, 8]
pop -> 8 stack [3]
pop -> 3 stack []
pop stack underflow
In C++
A fixed-capacity stack in C++ is a std::array plus a counter. std::stack in the standard library is an adapter over std::deque by default, with push, pop (which returns nothing) and top.
#include <array>
#include <cstdio>
#include <stack>
#include <stdexcept>
template <typename T, std::size_t N>
class Stack {
std::array<T, N> a_{};
std::size_t top_ = 0;
public:
void push(const T& x) {
if (top_ == N) throw std::overflow_error("stack overflow");
a_[top_++] = x;
}
T pop() {
if (top_ == 0) throw std::underflow_error("stack underflow");
return a_[--top_];
}
bool empty() const { return top_ == 0; }
};
int main() {
Stack<int, 4> s;
for (int x : {3, 8, 5}) s.push(x);
std::printf("pop -> %d\n", s.pop());
s.push(1);
while (!s.empty()) std::printf("pop -> %d\n", s.pop());
try { s.pop(); } catch (const std::underflow_error& e) { std::printf("%s\n", e.what()); }
std::stack<int> t; // the library adapter
for (int x : {3, 8, 5}) t.push(x);
std::printf("std::stack top %d, size %zu\n", t.top(), t.size());
}pop -> 5
pop -> 1
pop -> 8
pop -> 3
stack underflow
std::stack top 5, size 3
Matching brackets
A stack is exactly what you need when things must be closed in the reverse order they were opened. To check that a string of brackets is balanced, push every opening bracket; at every closing bracket, pop and check that the popped bracket is its partner. The string is balanced if no check fails and the stack ends empty. Each character costs , so the check is . This is the practice problem Valid Parentheses.
PAIRS = {")": "(", "]": "[", "}": "{"}
def balanced(text):
stack = []
for i, c in enumerate(text):
if c in "([{":
stack.append(c)
elif c in PAIRS:
if not stack:
return f"no: '{c}' at {i} closes nothing"
top = stack.pop()
if top != PAIRS[c]:
return f"no: '{c}' at {i} closes '{top}'"
return "yes" if not stack else f"no: {len(stack)} bracket(s) left open"
for t in ["a[i] = f(b[j], {k: (1, 2)})", "([)]", "(()", "x)("]:
print(f"{t:28} {balanced(t)}")a[i] = f(b[j], {k: (1, 2)}) yes
([)] no: ')' at 2 closes '['
(() no: 1 bracket(s) left open
x)( no: ')' at 1 closes nothing
Evaluating postfix expressions
In postfix (reverse Polish) notation an operator follows its operands: 3 4 + 2 * means . No parentheses are needed, and a stack evaluates it in one pass: push numbers; at an operator, pop the right operand, then the left one, and push the result. A well-formed expression leaves exactly one number. Compilers and calculators use the same idea, and the practice problem Evaluate Reverse Polish Notation asks for it.
def eval_postfix(tokens):
stack = []
for tok in tokens.split():
if tok in "+-*/":
right, left = stack.pop(), stack.pop() # order matters for - and /
stack.append({"+": left + right, "-": left - right,
"*": left * right, "/": int(left / right)}[tok])
else:
stack.append(int(tok))
print(f"{tok:>3}: {stack}")
assert len(stack) == 1, "malformed expression"
return stack[0]
print("value:", eval_postfix("5 1 2 + 4 * + 3 -")) 5: [5]
1: [5, 1]
2: [5, 1, 2]
+: [5, 3]
4: [5, 3, 4]
*: [5, 12]
+: [17]
3: [17, 3]
-: [14]
value: 14
The expression is . The stack never holds more than three values here; in general its depth is the nesting depth of the expression.
Note: The call stack of every program is a stack in this sense: a call pushes a frame with the arguments and the return address, and returning pops it. Recursion depth is stack depth, which is why a recursion 100,000 levels deep fails in Python (
RecursionError) and can crash a C++ program.
Test yourself
After push 1, push 2, pop, push 3, push 4, pop, pop, what is on the stack, bottom first?
- [1]
- [1, 2]
- [1, 3]
- [3]
In the array implementation, what does top hold?
- the index of the bottom element
- the number of elements, which is also the next free position
- the value of the top element
- the capacity
When evaluating 8 2 - with a stack, which value is popped first?
- 8, the left operand
- 2, the right operand
- 6, the result
- either, since subtraction commutes