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).
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.
Input: push(5), pop(), empty() Output: 5, true Push then pop returns 5, leaving the stack empty.
- 1 <= x <= 10^5 - At most 100 operations. - pop and top are only called on a non-empty stack.
A queue removes from the front, but a stack must remove the most recent element. The trick: after every push, rotate the queue so the newly added element sits at the front. Then the queue's front is always the stack's top, and pop/top are just front operations.
“Can I use a deque, or only a plain queue?”
Only queue operations — enqueue, dequeue, front, size — are assumed.
“Are pop and top ever called on an empty stack?”
No — they're guaranteed to be called only when the stack is non-empty.
A queue pops from the front, but a stack needs the newest element out first.
So after each push I rotate the queue: enqueue the new element, then move every earlier element behind it.
Now the front of the queue is always the stack top, so pop and top are front operations.
Worked example — push 1, push 2, top, pop
push 1 -> queue [1] (null) push 2 -> enqueue 2 -> [1,2], rotate 1 -> [2,1] (null) top -> front is 2 returns 2 pop -> dequeue 2 -> [1] returns 2
By rotating after each push, the queue's front always holds the most recently pushed element — exactly the stack's top.
Moving the size - 1 older elements behind the new one flips FIFO into LIFO for that element, and inductively keeps the whole queue in stack order.
The rotation makes push O(n); pop, top, and empty are O(1). (A push-cheap variant does the rotation during pop instead.)
Key takeaway
Use one queue and keep its front as the stack top by rotating after each push: enqueue the new element, then move the older size - 1 elements behind it. Then pop/top are front operations. Push is O(n); the rest O(1).
push(x): enqueue x; repeat size-1 times: enqueue(dequeue()) pop(): return dequeue() top(): return front() empty(): return size == 0