使用两个队列
class MyStack {
private Queue<Integer> a;//输入队列
private Queue<Integer> b;//输出队列
public MyStack() {
a = new LinkedList<>();
b = new LinkedList<>();
}
public void push(int x) {
a.offer(x);
// 将b队列中元素全部转给a队列
while(!b.isEmpty())
a.offer(b.poll());
// 交换a和b,避免重新把数据移回去
Queue temp = a;
a = b;
b = temp;
}
public int pop() {
return b.poll();
}
public int top() {
return b.peek();
}
public boolean empty() {
return b.isEmpty();
}
}