Where it runs
1. The problem
You can build node chains and cut them now. Next come two new structures: the stack and the queue. You can build them on such a chain or on a plain array. One rule sets them apart from a list: which end you add to and which end you take from. That one rule is enough for a surprising number of tasks.
The rule of a stack: you add on top and take from the top. You never take from the middle or the bottom. Add the numbers 1, 2, 3. The first one to come off is 3, then 2, then 1. This rule is called last in, first out (LIFO for short). Programs need it for undo history, the back button, checking brackets and the call stack. The call stack is the list of functions that have started and are waiting for the functions they called to finish. First you need the structure itself: a small class with a top that you put things on (push) and take them off (pop).
This step is part of the paid track
The first 33 steps are open to everyone: lesson, exercise and tests. This one opens with full access. Start with a free account and the free steps.
Create a free accountSee what is includedOn LeetCode
Problems where the newest item is the one you need next, such as undoing the last action or cancelling a character with the one before it. Push onto a stack and pop from the top.
Each operation reads or removes the last one or two scores, which is exactly push, pop and peek.
Push each letter, and pop instead when it equals the top of the stack.
A star pops the last letter kept, and what is left in the stack is the answer.
Push numbers, and on each operator pop two, compute, and push the result back.