思路:
一道很简单的题,就是栈是先进后出,队列是先进先出,用两个栈底相互对着,这样一个队列就产生了,右栈为空的情况,左栈栈底就是队首元素,所以我们需要将左栈全部压入右栈,右栈不为空,那么右栈就是之前压入过,这时右栈栈顶元素就是队首元素,大家画画图应该就明白了
class MyQueue {
Stack<Integer> left;
Stack<Integer> right;
public MyQueue() {
left = new Stack<>();
right = new Stack<>();
}
public void push(int x) {
left.push(x);
}
public int pop() {
if (right.isEmpty()) {
while (!left.isEmpty()) {
right.push(left.pop());
}
}
return right.pop();
}
public int peek() {
if (right.isEmpty()) {
while (!left.isEmpty()) {
right.push(left.pop());
}
}
return right.peek();
}
public boolean empty() {
return left.isEmpty() && right.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();
*/