How to recognise
nested pairs (brackets, tags), undo or "go back one step" (a path with ".."), evaluating an expression, or a stack that must also answer "what is the minimum?" at once, by keeping extra info such as the running minimum next to each entry.
How to solve problems like this
- Ask whether the latest unfinished thing must be finished first: an open bracket, a folder you went into, a number waiting for its operator.
- Push what is still open. When something closes it, pop the top and check or combine.
- Handle the edges: popping an empty stack, and items still on the stack at the end.
- If you also need the minimum (or maximum) at any moment, push it with each entry: the pair (value, minimum so far). Then the top always knows the answer in O(1).
Variant: Evaluate
The same, but the pile holds numbers: an operation takes the top two, works out the result and puts it back. That evaluates an expression with no brackets or precedence rules.
- Push every number as soon as you read it.
- On an operator, pop b first and a second: the top is the right operand, which matters for − and ÷.
- Push a op b back; at the end the stack holds exactly one number, the answer.
- For an ordinary expression with brackets, keep the result and sign so far; at "(" push them and start fresh, at ")" pop them and combine.
Where it's used
- Function calls. When a function calls another, the program pushes where to come back to. The latest call has to return first, so this is a stack, and a "stack overflow" error is that stack running out of room.
- Reading HTML. While reading a page, the browser keeps a stack of open tags. A closing tag closes the one on top of the stack; that is how the HTML standard describes the parser.
- Undo. Ctrl+Z in an editor undoes the last action first, then the one before it: the actions lie on a stack.