A lesson from the Data Structures module of the bootcamp. About an 11 minute read.
A stack is last in, first out. You only touch the top, and that one restriction is the whole point: it is exactly the right memory for anything nested. It is also what your language uses to run function calls, so every recursive tree traversal you write is a stack, whether you can see it or not.
A stack is a sequence where you push onto the top and pop off the top, and there is no way to reach into the middle. That sounds like a limitation, and it is. It is also why the structure is useful. A stack is not a worse list. It is a list with a rule attached, and the rule happens to be the exact shape of nesting: the last thing you opened is the first thing that has to close. That is true of brackets, HTML tags, function calls, undo history, and the path from a tree's root down to wherever you are now. When a structure's rule matches a problem's rule, the code stops needing to check anything.
The rest of this lesson continues with 5 further sections. See the full curriculum.
Browse all 576 practice puzzles