Stacks and queues · Exercise 62 of 100
Stack
To push a value onto a stack, add it to the end of a list and treat that end as the top. To pop, remove the last value after checking that the list has one. Using the same end for both operations makes the newest value the first one out.
Try it yourself
An editor pushes change IDs 12 and 25, in that order, onto an empty undo stack. Each undo pops one ID. The editor undoes once, pushes change 38, then undoes twice more. Which ID does the final undo remove?
One-step hint
Draw the undo history from bottom to top. Erase the top entry for the first undo before adding the next change above the surviving history.
Worked solution
- The first undo removes 25 and leaves 12. The editor then places 38 on top of 12.
- The next undo removes 38, exposing 12 at the top. The final undo therefore removes 12.