Linked lists · Exercise 25 of 100
Build a queue with stacks
A queue removes the oldest item first, so push arrivals onto an input stack and take departures from an output stack. When a departure is needed and the output stack is empty, move all input items onto it one at a time to bring the oldest to the top. While the output stack still holds items, its top is next in line.
Try it yourself
Starting empty, enqueue 20, 30, and 40 in that order. Dequeue once, then enqueue 50. What value does the next dequeue return?
One-step hint
Draw separate input and output stacks. After the first dequeue, keep the output stack in place while the new arrival goes onto input.
Worked solution
- Transfer 40, then 30, then 20 to the output stack. The first dequeue removes 20 and leaves 30 on top.
- The new arrival 50 stays on the input stack because the output stack still holds older items. The next dequeue takes 30.