A queue is first-in, first-out: elements leave in the order they arrived, like a line at a shop. A stack is the opposite (last-in, first-out). Curiously, two stacks can simulate a queue: reversing a stack into another stack flips its order.
A deli writes each order on a paper slip, and the counter has only two spikes to hold slips: a slip can go onto the top of a spike or come off the top, nothing else. Orders must still be served in the order they arrived. Write a class MyQueue that does this with two Python lists standing in for the spikes (use only append, pop() from the end, a look at the last element and an emptiness check). It needs these methods:
push(x)– orderxjoins the back of the queue.pop()– serve the oldest waiting order: remove it and return it.peek()– return the oldest waiting order without serving it.empty()– returnTruewhen no order is waiting, otherwiseFalse.
pop and peek are only called while at least one order is waiting. The tests call the methods in sequence with run_ops and compare the list of return values (None for methods that return nothing).
Examples
Input: ops = ["MyQueue", "push", "push", "pop", "push", "peek", "empty"]
args = [[], [7], [3], [], [9], [], []]
Output: [None, None, None, 7, None, 3, False]
Explanation: 7 arrived first, so it is served first; then 3 is the oldest waiting order, with 9 still behind it.
Constraints
- At most 100 operations per test
1 <= x <= 100
Goals
- Explain the difference between FIFO (queue) and LIFO (stack) order
- Build one data structure out of another and keep state across method calls
- Move elements between stacks lazily so that each element is transferred at most once