Stack Using Queues
Rotate the queue after each push so the newest item sits at the front.
Decision · step 4 of 18Stack: Built from one queue: rotate after each push
3 is behind 1 older item. Each rotation dequeues the front and enqueues it at the back, so after 1 rotations every older item has gone round once and 3 is at the front.
What you will see
After a push, the earlier items cycle to the back one by one.
Cost
| Best | O(1) |
|---|---|
| Average | O(n) |
| Worst | O(n) |
| Space | O(n) |
Push is O(n)pop O(1) in this variant.
How you work with it here
play it through, step one change at a time, scrub to any step, run it on your own input, predict what happens next, try operations in any order.
Screen readers: Items announce position from the top or front and value; each step announces the operation and the new top or front.
Reduced motion: Items appear or disappear in place with a crossfade instead of sliding in or out.