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 JSONEdit the lesson input, then build a deterministic source-linked trace.
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.
Current operation
Trace stateReady 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
JavaStackWithTwoQueues.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