Implement Stack using Queues

Build a last-in-first-out stack using only queue operations: add to the back, remove from the front, read the front, size and is-empty. Support push (put on top), pop (remove and return the top), top (read the top) and empty.

30:00

Implement Stack using Queues
easy
Free written solution
Topics
Companies

Build a last-in-first-out stack using only queue operations: add to the back, remove from the front, read the front, size and is-empty. Support push (put on top), pop (remove and return the top), top (read the top) and empty.

Example 1:
Input: {"commands":["MyStack","push","push","top","pop","empty"],"values":[[],[1],[2],[],[],[]]}
Output: [null,null,null,2,2,false]
Constraints:
  • 1≤x≤91 \leq x \leq 9

  • At most 100100 calls are made to push, pop, top, and empty.

  • All calls to pop and top are valid (the stack is not empty).

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"commands":["MyStack","push","push","top","pop","empty"],"values":[[],[1],[2],[],[],[]]}
new
push(1)
push(2)
top()
pop()
empty()

6 calls to run. One queue holds everything; its front will always be the top of the stack.

the one queue

▼

dequeue front, enqueue back

front
= top

empty

back
in

value being pushed

just rotated

front

what the caller sees

(empty)

stack, top first

returned values

[]

total rotations: 0 (push is O(n), pop and top are O(1))

Variables
VariableValue
call
q[]
output[]
DepthFunction Call
Stack empty
0/8