请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push
、pop
、peek
、empty
)
input:["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
output:[null, null, null, 1, 1, false]
class MyQueue {
Deque<Integer> deque1;
Deque<Integer> deque2;
public MyQueue() {
deque1 = new LinkedList<Integer>();
deque2 = new LinkedList<Integer>();
}
public void push(int x) {
deque2.push(x);
}
public int pop() {
if(deque1.isEmpty()){
reverse();
}
return deque1.pop();
}
public int peek() {
if(deque1.isEmpty()){
reverse();
}
return deque1.peek();
}
public boolean empty() {
return deque1.isEmpty() && deque2.isEmpty();
}
public void reverse(){
while(!deque2.isEmpty()){
deque1.push(deque2.pop());
}
}
}
/**
* 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();
*/