Skip to content
Onsite

Stack Using Two Queues

EasyP2Coding

Implement a last-in-first-out stack using only queue operations: add to the back, remove from the front, look at the front, check the size and check if empty.

Implement the MyStack class:

  • push(x) pushes x onto the stack.
  • pop() removes the top element and returns it.
  • top() returns the top element without removing it.
  • empty() returns true if the stack has no elements.

pop and top are only called on a non-empty stack. In JavaScript, treat an array as a queue by using only push and shift; in Python use collections.deque with append and popleft.

Example 1

Input
["MyStack","push","push","top","pop","empty"] [[],[1],[2],[],[],[]]
Output
[null,null,null,2,2,false]

Constraints

  • 1 <= x <= 9
  • At most 100 calls to push, pop, top and empty
  • pop and top are only called when the stack is non-empty

Hints

Run checks the 2 visible tests, Submit all 5.