Stacks and queues · Exercise 63 of 100

Queue

A queue adds each new item at the back so it waits behind earlier arrivals. To remove an item, check that the queue has at least one item and take the one at the front.

Try it yourself

Jobs 41, 18, 63 and 25 enter an empty printer queue in that order. The printer takes two jobs, then job 12 arrives. Which job number will the printer take next?

One-step hint

Draw the jobs in arrival order and cross off the first two. Add the new arrival at the back and look at the frontmost uncrossed job.

Worked solution
  1. The printer takes 41 and then 18 from the front, leaving 63 ahead of 25.
  2. Job 12 joins behind 25, so 63 is still at the front and will be taken next.
DSA compiler

Explore the idea visually in the queues lab.