题目:
算法思想:
使用辅助队列操作
代码:
class MyQueue {
Stack<Integer> s1;
Stack<Integer> s2;
public MyQueue() {
s1 = new Stack<>();
s2 = new Stack<>();
}
public void push(int x) {
s1.push(x);
}
public int pop() {
while(!s1.isEmpty()) {
int pop = s1.pop();
s2.push(pop);
}
int top = s2.pop();
while(!s2.isEmpty()) {
int pop = s2.pop();
s1.push(pop);
}
return top;
}
public int peek() {
while(!s1.isEmpty()) {
int pop = s1.pop();
s2.push(pop);
}
int top = s2.peek();
while(!s2.isEmpty()) {
int pop = s2.pop();
s1.push(pop);
}
return top;
}
public boolean empty() {
if(!s1.isEmpty()) {
return false;
} else {
return true;
}
}
}
/**
* 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();
*/