232 Implement Queue using Stack
Implement the following operations of a queue using stacks.
- push(x) -- Push element x to the back of queue.
- pop() -- Removes the element from in front of queue.
- peek() -- Get the front element.
- empty() -- Return whether the queue is empty.
Notes:
- You must use
only
standard operations of a stack -- which means only
push to top,peek/pop from top,size, andis emptyoperations are valid. - Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
- You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
Solution)
First, we can use two Stacks to implement Queue.
If the push (enqueue) is called, we can push it to the first stack.
If the pop (dequeue) is called, we can pop from the second stack. If the second stack is empty, we can move from the first stack to the second stack.
class MyQueue {
private Stack<Integer> firstStack, secondStack;
/** Initialize your data structure here. */
public MyQueue() {
firstStack = new Stack<>();
secondStack = new Stack<>();
}
private void move() {
while(!firstStack.empty())
secondStack.push(firstStack.pop());
}
/** Push element x to the back of queue. */
public void push(int x) {
firstStack.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if (secondStack.empty())
move();
return secondStack.pop();
}
/** Get the front element. */
public int peek() {
if (secondStack.empty())
move();
return secondStack.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return firstStack.empty() && secondStack.empty();
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/