A queue hands its values back in the order they arrived, like a line at a shop: the first value pushed is the first one to leave. A stack does the opposite: the last value pushed leaves first. Build a queue out of two stacks, using only what a stack can do: add a value on top, look at or remove the top value, and check whether it is empty.
Implement the class MyQueue:
MyQueue()creates an empty queue.push(x)adds the integerxat the back of the queue.peek()returns the value at the front of the queue, without removing it.pop()removes the value at the front of the queue and returns it.empty()returnsTrueif the queue holds no values, andFalseotherwise.
The input is a list of operations, applied in order to one new MyQueue. The output lists what the peek, pop and empty calls return, in order. The starter code spells these names the way your language does.
Example 1:
Input:
push(1)
push(2)
peek()
pop()
empty()
Output: 1 1 False
Explanation:
1 arrived first, so it is at the front: peek() returns 1, and pop() removes it and returns it.
2 is still in the queue, so empty() is False.
Example 2:
Input:
push(1)
push(2)
pop()
push(3)
peek()
pop()
pop()
empty()
Output: 1 2 2 3 True
Explanation:
pop() returns 1, the first value pushed. 3 arrives next, but 2 has been waiting longer,
so peek() and the next pop() return 2, and only then does pop() return 3. The queue is empty again.
Example 3:
Input:
empty()
push(7)
empty()
pop()
empty()
Output: True False 7 True
Explanation: A new queue is empty. After push(7) it isn't, and after pop() returns 7 it is empty again.
Constraints:
1 <= x <= 109popandpeekare only called when the queue is not empty.- At most
2 * 105calls in total are made topush,pop,peekandempty.
Note:
Each operation should take O(1) time amortized: one pop or peek may have to move many values from one stack to the other, but each value is moved at most once, so n operations take O(n) time in total. Moving all the values over and back again on every pop would take O(n) time per call, where n is the number of values in the queue.
Free plan: 30 tutor messages. PRO is unlimited.
