Pattern visualizer
Implement Stack using Queues
A plain queue always serves its oldest item first — the opposite of what a stack needs. Fix it at push time instead of read time: enqueue the new value at the back, then rotate the queue by dequeuing-and-re-enqueuing every OLDER element exactly (size-1) times. That walks every old item around to the back, leaving the just-pushed value sitting at the front — so the queue's front always matches the stack's top. Animated on: Build a LIFO stack (push, top, pop, empty) using only one FIFO queue..
Rotate-on-push turns one queue into a LIFO
Start with one empty queue. A single rotation trick on every push will make it behave like a LIFO stack.
1MyStack: keep a single FIFO queue2 the queue is initially empty3 push(x):4 add x at the back of the queue5 repeat (queue size - 1) times: remove the front and add it back at the back6 top(): return the front of the queue7 pop(): remove and return the front of the queue8 empty(): return whether the queue is empty
← / → step · space play · Home restart