Stacks: last in, first out
A stack allows two main operations: push puts an item on top, pop takes the top item off. The last item in is the first out (LIFO). You can also peek at the top without removing it. All three are O(1).
A stack is the natural structure for anything that has to be undone or unwound in reverse order. Your program's call stack is one: each function call pushes a frame, each return pops it. That's also why infinite recursion ends in a 'stack overflow': the stack ran out of room.
Undo in an editor (each action pushed, undo pops the last one), the browser's back button, matching brackets in code: every '(' is pushed, every ')' pops and must match.
In code: Python · Rust
undo = []
undo.append("typed 'a'") # push
undo.append("bold")
undo.pop() # 'bold': last in, first out
undo[-1] if undo else None # peeklet mut undo: Vec<&str> = Vec::new();
undo.push("typed 'a'");
undo.push("bold");
let last = undo.pop(); // Some("bold")
let top = undo.last(); // peek: Some("typed 'a'")- In both languages a plain dynamic array (list, Vec) is the idiomatic stack: push and pop at the end are O(1).
- Python's default recursion limit (about 1000 frames) is a guard against the call stack overflowing.