4/36
Part 1 of 8 · Last in, first outLearn and do
A stack fits whenever the last thing opened must close first
When does a problem call for a stack? Brackets are the clearest case.
( )opened first, closed last
[ ]around 0
{ }around k: v
Each closer pairs with the most recent opener that's still open. The ] closes the [, the } closes the {, and only then can the ) close the (.
Reach for a stack whenever the thing you deal with next is the most recent thing that isn't finished yet:
- An editor's undo pushes each edit and pops the latest one.
- In code, the bracket that must close next is the last one opened.
- In a running program, the function that returns next is the one called most recently. That's the call stack, the subject of part 2.
Undo, first on that list, is the plainest stack. In the editor, write typed(actions): each action is a word to type, or "undo", which takes back the latest word still there. Return the words left, joined by spaces.