请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push、top、pop 和 empty)。
实现 MyStack 类:
- void push(int x) 将元素 x 压入栈顶。
- int pop() 移除并返回栈顶元素。
- int top() 返回栈顶元素。
- boolean empty() 如果栈是空的,返回 true ;否则,返回 false 。
注意:
- 你只能使用队列的基本操作 —— 也就是 push to back、peek/pop from front、size 和 is empty 这些操作。
- 你所使用的语言也许不支持队列。 你可以使用 list (列表)或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/implement-stack-using-queues
解题思路:
与用Java用栈实现队列不同,用两个队列去实现栈,队列的作用就不是分别指代进出了,而是一个队列对另一个队列的备份作用。对于pop,empty,top等操作,可以在队列上直接完成,但对于入栈,较为复杂,要把握“先入后出”;当que1为空时,将原本的要传入que1的元素,先压入que2,然后将que1与que2队列互换;当que1不为空时,先将元素传入que2后,再将que1的元素,通过队列的方式,“先进先出” 压入que2,再互换que1与que2的位置,得到的que1就是模拟的栈stack;
代码实现:
前置知识:
```java
boolean offer(E e)
将指定的元素插入此队列(如果立即可行且不会违反容量限制),当使用有容量限制的队列时,此方法通常要优于 add(E),后者可能无法插入元素,而只是抛出一个异常。
E poll()
:获取并移除此队列的头,如果此队列为空,则返回 null。
代码实现
class MyStack {
Queue<Integer> queue1; // 和栈中保持一样元素的队列
Queue<Integer> queue2; // 辅助队列
/** Initialize your data structure here. */
public MyStack() {
queue1 = new LinkedList<>();
queue2 = new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
queue2.offer(x); // 先放在辅助队列中
while (!queue1.isEmpty()){
queue2.offer(queue1.poll());
}
Queue<Integer> queueTemp;
queueTemp = queue1;
queue1 = queue2;
queue2 = queueTemp; // 最后交换queue1和queue2,将元素都放到queue1中
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return queue1.poll(); // 因为queue1中的元素和栈中的保持一致,所以这个和下面两个的操作只看queue1即可
}
/** Get the top element. */
public int top() {
return queue1.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return queue1.isEmpty();
}
}
**优化方法:**只用一个队列,当然本题指明要用两个队列,作为拓展
**主要思路:**用一个队列模拟栈的出栈操作时,先将队列头部的元素移到队列的末尾,直至移到最后一个元素时,将其压出,此时,弹出的元素就是栈顶需要出栈的元素。
class MyStack {
Queue<Integer> queue;
public MyStack() {
queue = new LinkedList<>();
}
//每 offer 一个数(A)进来,都重新排列,把这个数(A)放到队列的队首
public void push(int x) {
queue.offer(x);
int size = queue.size();//计算队列的大小
//移动除了 A 的其它数
while (size-- > 1)
queue.offer(queue.poll());
}
public int pop() {
return queue.poll();
}
public int top() {
return queue.peek();
}
public boolean empty() {
return queue.isEmpty();
}
}