Computer Science I / Stacks and Queues
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.

Hints
  1. Track the stack contents through every operation before deciding which value leaves when.
  2. The first value pushed cannot leave until everything pushed above it has gone.
Show the answer
  1. 2
  2. 4
  3. 3
  4. 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.

Read the lesson: Stacks and Queues →

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.

More questions on Stacks and Queues