题目
题解思路
根据题意,要用两个队列来实现栈,首先我们知道,队列是先进先出,栈是后进先出。
知道了以上要点,我们两个队列的用处也就一目了然了。
一个队列为主队列,一个为辅助队列,当入栈操作时,我们先将主队列内容导入辅助队列,然后将入栈元素放入主队列队头位置,再将辅助队列内容,依次添加进主队列即可。
代码
class MyStack {
private Queue<Integer> queOne;
private Queue<Integer> queTwo;
public MyStack() {
queOne = new LinkedList();
queTwo = new LinkedList();
}
public void push(int x) {
queTwo.offer(x);
while (!queOne.isEmpty()) {
queTwo.offer(queOne.poll());
}
Queue temp = new LinkedList();
temp = queOne;
queOne = queTwo;
queTwo = temp;
}
public int pop() {
return queOne.poll();
}
public int top() {
return queOne.peek();
}
public boolean empty() {
return queOne.isEmpty();
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/