Leetcode 232. Implement Queue using Stacks
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
, pop
, peek
, and empty
).
Implement the MyQueue
class:
void push(int x)
Pushes element x 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()
Returns true
if the queue is empty, false
otherwise.Notes:
push to top
, peek/pop from top
, size
, and is empty
).pop
or peek
will be made on an empty queue).To implement a queue using two stacks, we can use two main stacks:
stack_in
): Used to handle incoming elements via the push
operation.stack_out
): Used to handle outgoing elements for pop
and peek
operations.The main idea is to transfer elements from the input stack to the output stack when needed, ensuring that the order of elements in the output stack is such that the topmost element is the front of the queue.
Operations:
stack_in
.stack_out
is empty, transfer all elements from stack_in
to stack_out
(reversing their order). Then, pop the top element from stack_out
.pop
, but instead of popping the top element from stack_out
, simply return it.true
if both stack_in
and stack_out
are empty.import java.util.Stack;
class MyQueue {
private Stack<Integer> stack_in;
private Stack<Integer> stack_out;
public MyQueue() {
stack_in = new Stack<>();
stack_out = new Stack<>();
}
public void push(int x) {
stack_in.push(x);
}
public int pop() {
if (stack_out.isEmpty()) {
while (!stack_in.isEmpty()) {
stack_out.push(stack_in.pop());
}
}
return stack_out.pop();
}
public int peek() {
if (stack_out.isEmpty()) {
while (!stack_in.isEmpty()) {
stack_out.push(stack_in.pop());
}
}
return stack_out.peek();
}
public boolean empty() {
return stack_in.isEmpty() && stack_out.isEmpty();
}
}
push
operation to the stack.stack_out
is empty and elements need to be transferred from stack_in
. However, amortized over a sequence of (m) operations, the complexity is (O(1)) per operation because each element is moved at most once.stack_in
to stack_out
, but similar to pop
, the amortized complexity is (O(1)).This implementation provides an efficient and correct solution to the problem of simulating a queue using two stacks.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?