Implement Stack using Queues

Easy · Queue & Deque · about 10 minutes

Asked at Google, Amazon, Bloomberg, Microsoft.

Implement a LIFO stack using only queue operations (push to back, pop/peek from front, size, empty).

  • MyStack() creates the stack.
  • push(x) pushes x; pop() removes and returns the top; top() returns the top; empty() reports

whether the stack is empty.

Calls to pop and top are always valid.