Implement Queue using Stacks
Implement Queue using Stacks
QueueStackDesign
Problem Statement
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:
MyQueue()
initializes the object.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.
Example
Example 1:
Operation Sequence:
push(1)returns: 1
push(2)returns: 2
peek()returns: 1
pop()returns: 1
empty()returns: false
Solution
The core idea is to use two stacks, `s1` and `s2`, to simulate a queue. `s1` will be used for push operations, and `s2` will be used for pop and peek operations. This amortized approach gives us O(1) time complexity for most operations.
Algorithm Steps
- For `push`, simply push the element onto `s1`.
- For `pop` and `peek`, if `s2` is empty, we must transfer all elements from `s1` to `s2`. This reverses the order, giving us the FIFO behavior.
- After the potential transfer, `pop` removes and returns the top of `s2`, and `peek` returns the top of `s2` without removing it.
- The queue is `empty` if both stacks are empty.
Stack 1 (for push)
Stack 2 (for pop/peek)
Start with two empty stacks.
Implement Queue using Stacks Solution