Implement Queue using Stacks⚓︎
Description⚓︎
Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push
, peek
, pop
, and empty
).
Implement the MyQueue
class:
void push(int x)
Pushes elementx
to the back of the queue.int pop()
Removes the element from the front of the queue and returns it.int peek()
Returns the element at the front of the queue.boolean empty()
Returnstrue
if the queue is empty,false
otherwise.
Notes:
- You must use only standard operations of a stack, which means only
push to top
,peek/pop from top
,size
, andis empty
operations are valid. - Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations.
Example 1:
- Input:
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
- Output:
[null, null, null, 1, 1, false]
Explanation:
Constraints:
1 <= x <= 9
- At most
100
calls will be made topush
,pop
,peek
, andempty
. - All the calls to
pop
andpeek
are valid.
Solution⚓︎
Implementation Using Two Stacks⚓︎
When pushing data, it is sufficient to simply place the data into the input stack. However, popping data is a bit more complex. If the output stack is empty, then all the data from the input stack should be transferred into it (note that it should be a complete transfer), and then data can be popped from the output stack. If the output stack is not empty, data can be directly popped from it.
Finally, how do we determine if the queue is empty? If both the input and output stacks are empty, then the simulated queue is considered empty.
Way 1⚓︎
- Time complexity:
push
andempty
are \(O(1)\),pop
andpeek
are \(O(n)\); - Space complexity: \(O(n)\).
Way 2⚓︎
We use a stack to store the elements of the queue, and an auxiliary stack to aid in the implementation of the pop()
and peek()
operations.
The four operations are implemented as follows:
push(x)
: insertsx
directly into the top of the stack;pop()
: if we need to pop the bottom element of the stack, we first insert all elements above the bottom of the stack into the auxiliary stack, then pop the bottom element, and finally re-press the elements of the auxiliary stack into the current stack;peek()
: returns the top element of the stack. Similarly, we first insert all elements above the bottom of the stack into the auxiliary stack, then eject the bottom element, and finally re-press the elements in the auxiliary stack into the current stack to restore the current stack to its original state;empty()
: returns whether the current stack is empty.