Implement Stack using Queues

easy

Implement a last-in-first-out stack using only a queue (a FIFO structure). Support:

  • push(x) — push x onto the top.
  • pop() — remove and return the top element.
  • top() — return the top element without removing it.
  • empty() — return whether the stack is empty.

pop and top are only called on a non-empty stack. Use standard queue operations (enqueue at the back, dequeue from the front, peek front, size).

Hints

A queue removes from the front, but a stack needs the newest element out first.
After pushing, rotate the queue so the new element sits at the front.
Then pop and top are just front-of-queue operations.

Common doubts

It keeps the invariant that the queue's front is the stack's top, so the front operations a queue offers directly implement pop and top.
Yes — a two-queue variant leaves push cheap and does the reordering during pop, moving all but the last element to a second queue.
Exactly size - 1: everything except the element you just enqueued, so that element ends up at the front.

Interview follow-ups

Push to a main queue; on pop, dequeue all but the last element into a second queue, return the last, then swap the queues.
They have the same amortized cost; choose based on whether pushes or pops dominate your workload.

Fun facts

  • Implementing one abstract structure with another is a classic reduction — it proves the two are equally expressive.
  • The rotation trick is the same 'rotate a ring' idea used in round-robin scheduling.

Asked at

AmazonMicrosoftGoogle
Frequently Sometimes Occasionally
Example 1
Input: push(1), push(2), top(), pop(), empty()
Output: 2, 2, false
top and pop both see 2 (the most recent); after popping, the stack still has 1, so empty is false.
Example 2
Input: push(5), pop(), empty()
Output: 5, true
Push then pop returns 5, leaving the stack empty.
Constraints

- 1 <= x <= 10^5 - At most 100 operations. - pop and top are only called on a non-empty stack.

Solve this problem →