使用两个队列来实现栈,主要就是在pop()或者top()操作的时候进行两次倒买倒卖。
不想整理代码了,明天弄了
public class MyStack {
Queue<Integer> q1;
Queue<Integer> q2;
public MyStack() {
q1 = new LinkedList<>();
q2 = new LinkedList<>();
}
public void push(int x) {
q1.add(x);
}
public int pop() {
int result = 0;
while (!empty()) {
int temp = q1.remove();
if (q1.isEmpty()) {
result = temp;
} else {
q2.add(temp);
}
}
while (!q2.isEmpty()) {
q1.add(q2.remove());
}
return result;
}
public int top() {
int result = 0;
while (!empty()) {
int temp = q1.remove();
if (q1.isEmpty()) {
result = temp;
}
q2.add(temp);
}
while (!q2.isEmpty()) {
q1.add(q2.remove());
}
return result;
}
public boolean empty() {
return q1.isEmpty();
}
}