Visualize

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

time O(n) push, O(1) pop/topspace O(n)step 1 / 8
line 2

Start with one empty queue. A single rotation trick on every push will make it behave like a LIFO stack.

Pseudocode
1MyStack: keep a single FIFO queue
2 the queue is initially empty
3 push(x):
4 add x at the back of the queue
5 repeat (queue size - 1) times: remove the front and add it back at the back
6 top(): return the front of the queue
7 pop(): remove and return the front of the queue
8 empty(): return whether the queue is empty

← / → step · space play · Home restart

Where to practice Queue