Practice question · Put in order
A stack starts empty and these operations run in order: push 1, push 2, pop, push 3, push 4, pop, pop, pop. Order the four popped values by when they came out.
- 3
- 4
- 1
- 2
Hints
- Track the stack contents through every operation before deciding which value leaves when.
- The first value pushed cannot leave until everything pushed above it has gone.
Show the answer
- 2
- 4
- 3
- 1
Why
The pops give 2, then 4, then 3, then 1. Notice that 1 was pushed first and popped last, while 3 was pushed after 2 yet came out after 4, a stack's output order depends on the interleaving of pushes and pops, not simply on the reverse of the push order.
Practise Stacks and Queues
The app has 7 more questions on this lesson, and keeps your place in the course. Computer Science I is free to start.