232 Implement Queue using Stacks
Last updated
Last updated
class MyQueue {
Stack<Integer> oldStack;
Stack<Integer> newStack;
/** Initialize your data structure here. */
public MyQueue() {
oldStack = new Stack<>();
newStack = new Stack<>();
}
/** Push element x to the back of queue. */
public void push(int x) {
while (!oldStack.isEmpty()) {
newStack.push(oldStack.pop());
}
newStack.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
while (!newStack.isEmpty()) {
oldStack.push(newStack.pop());
}
return oldStack.pop();
}
/** Get the front element. */
public int peek() {
while (!newStack.isEmpty()) {
oldStack.push(newStack.pop());
}
return oldStack.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return oldStack.isEmpty() && newStack.isEmpty();
}
}
/**
* 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();
*/