Implement Queue using Stacks
EasyStack
Decode it first. Clues, constraints, pattern and plan before any code.Build a first-in, first-out queue class MyQueue using only two stacks (lists used only with push to the end, pop from the end, look at the end, and size). It supports:
push(x)addsxto the back of the queue.pop()removes the front element and returns it.peek()returns the front element without removing it.empty()returns whether the queue is empty.
q = MyQueue()
q.push(1); q.push(2)
q.peek() → 1
q.pop() → 1
q.empty() → falseEach operation should take amortised O(1) time.
Constraints
1 <= x <= 9- At most
100calls are made in total. popandpeekare only called on a non-empty queue.