Linked lists · Exercise 24 of 100
Build a stack with queues
A stack removes the newest item first, so keep that item at the front of the active queue. To push, put the new item in an empty spare queue, move the active queue's items behind it from front to back, then swap the queues' roles. To pop from a nonempty stack, remove the front item of the active queue.
Try it yourself
Start empty, push 18, push 25, and pop once. Then push 32 and pop twice. What value does the last pop return?
One-step hint
After each push, put the new item at the front of the simulated stack. Cross out the front item for each pop, including consecutive pops.
Worked solution
- Pushing 25 puts it in front of 18. The first pop removes 25 and leaves 18.
- Pushing 32 puts it in front of 18. The next pop removes 32, so the last pop returns 18.