DSAVisualiseData Structures & Algorithms Studio
Lists & Stacks Medium

Stack Emulation with Two Queues

StackWithTwoQueues keeps the stack top at queue1's front. Each push appends the new item to queue2, transfers the old queue1 entries behind it, and swaps the queue references.

Trace input

Bounded JSON

Edit the lesson input, then build a deterministic source-linked trace.

This lesson validates its own input and operation limits.

Source scenarios

Complexity

BestO(1) for peek, pop, and empty
AverageO(n) for push; O(1) for other operations
WorstO(n) for push; O(1) for other operations
SpaceO(n) across two queues

Array state

Follow the active comparisons and writes.

Live snapshot

Current operation

Trace state
Ready to explore
Source behavior & common mistakes

Trace how a push moves every older entry to queue2 before the two queue references switch. Peek and pop operate at queue1's front; empty reads queue1 directly.

  • The newly pushed entry must be the first entry in queue2 before old entries transfer.
  • A transfer removes the queue1 front and appends the same entry to queue2, preserving its identity.
  • Push swaps the queue references only after queue1 is empty.
  • Peek does not remove the front entry; pop does.
  • Peek and pop throw EmptyStackException when empty, while ArrayDeque.add(null) throws NullPointerException before changing either queue.

Algorithm code

Java
StackWithTwoQueues.java (pinned repository source)Step linked
The highlighted line follows the current step.

Ready to begin

Press Play to see what happens.

Detailed execution
Snapshot 1 / 1