请你仅使用两个队列实现一个后入先出(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.com/problems/implement-stack-using-queues
基本思路:通过观察,我们可以知道,题目的要求是通过两个队列来实现栈
。
并且我们知道队列是一种先进先出的数据结构
。那么我们该怎么样才能够通过两个队列实现栈这种后进先出的数据结构呢?
我们可以看看一下leetcode中官方题解,它的动态演示我觉得挺好的。如果还是不能理解的话,那么请看下面的过程分析:
由上面的分析,我们可以知道,遍历queue1,得到的序列就是栈。所以再判断栈是否为空、获取栈顶元素、跳出栈顶元素,操作对象都是queue1。 因为我们每一次插入新元素的时候,都有保证了queue2中所有的元素都跳出,并且压入到了queue1中。所以经过插入操作之后,queue2必然已经是空的了,所以不会存在queue2不为空的情况,所以最后进行pop、top、empty等操作的时候,只有queue1是操作对象,而不是queue2,或者两者
。
对应的代码:
class MyStack {
Queue<Integer> queue1;
Queue<Integer> queue2;
/** Initialize your data structure here. */
public MyStack() {
queue1 = new LinkedList<Integer>();
queue2 = new LinkedList<Integer>();
}
/** Push element x onto stack. */
public void push(int x) {
while(!queue1.isEmpty()){
queue2.offer(queue1.poll());
}
//将新元素压入到队列1中
queue1.offer(x);
while(!queue2.isEmpty()){
//如果队列2为空,那么将从队列2不断跳出元素,并将这些元素压入到队列1中
queue1.offer(queue2.poll());
}
/*
//如果队列1不为空,那么将所有的元素从队列1中跳出,并压入到队列2中
while(!queue1.isEmpty()){
queue2.offer(queue1.poll());
}
*/
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return queue1.poll();
}
/** Get the top element. */
public int top() {
return queue1.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return queue1.isEmpty();
}
}