一、题目描述
二、思路分析
2.1 分析
**队列的特点是先进先出,而栈是先进后出。**队列的队首元素也就是栈顶元素,从题目已知,我们可以用的队列的方法只有添加新元素到队尾,从队首查看或者移除元素。那问题就转换为怎么拿到队尾的元素呢?可以用两个队列实现,一个真实队列 realQueue 用于存放入队元素,一个虚拟队列 dummyQueue 存放出队元素。当入栈操作时,直接将元素入 realQueue。出栈操作时,将 realQueue 队列的元素出队到 dummyQueue 中。直到 realQueue 中只剩下一个元素,出队并将其保存下来,它就是出栈的元素。而此时的 dummyQueue 存放的就是 realQueue 中的元素了,只要将他们互相交换一下地址就好了。这样子的话,dummyQueue 重新变为空队列,realQueue 又变为存放元素的队列了。查看栈顶元素也是一样的思路。判断栈是否为空,只需要判断 realQueue 的情况就好了。
2.2 图解
- 参考代码随想录的用队列实现栈的动画演示
三、题解
- 用队列模拟栈的实现
class MyStack {
private Queue<Integer> realQueue;
private Queue<Integer> dummyQueue;
/** Initialize your data structure here. */
public MyStack() {
realQueue = new LinkedList();
dummyQueue = new LinkedList();
}
/** Push element x onto stack. */
public void push(int x) {
realQueue.offer(x);
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
while (realQueue.size() > 1) {
dummyQueue.offer(realQueue.poll());
}
int ret = realQueue.poll();
// 交换两个队列,让 realQueue 重新变为存放元素的队列
// 也可以直接循环把 dummyQueue 的元素全部放入 realQueue 中
Queue<Integer> tmp = realQueue;
realQueue = dummyQueue;
dummyQueue = tmp;
return ret;
}
/** Get the top element. */
public int top() {
int ret = 0;
while (realQueue.size() > 0) {
if (realQueue.size() == 1) {
// 保存栈顶元素
ret = realQueue.peek();
}
dummyQueue.offer(realQueue.poll());
}
Queue<Integer> tmp = realQueue;
realQueue = dummyQueue;
dummyQueue = tmp;
return ret;
}
/** Returns whether the stack is empty. */
public boolean empty() {
return realQueue.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();
*/