By Long Luo
Leetcode 232. 用栈实现队列 ,难度为Easy :
用栈实现队列 请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(\(\texttt{push}\) 、\(\texttt{pop}\) 、\(\texttt{peek}\) 、\(\texttt{empty}\) ):
实现\(\texttt{MyQueue}\) 类:
\(\texttt{void push(int x)}\) 将元素\(x\) 推到队列的末尾\(\texttt{int pop()}\) 从队列的开头移除并返回元素\(\texttt{int peek()}\) 返回队列开头的元素\(\texttt{boolean empty()}\) 如果队列为空,返回\(\textit{true}\) ;否则,返回\(\textit{false}\) 。说明:
你 只能 使用标准的栈操作 —— 也就是只有push to top
, peek/pop from top
, size
, 和is empty
操作是合法的。 你所使用的语言也许不支持栈。你可以使用list
或者deque
(双端队列)来模拟一个栈,只要是标准的栈操作即可。
示例 1:1 2 3 4 5 6 7 8 9 10 11 12 13 输入: ["MyQueue", "push", "push", "peek", "pop", "empty"] [[], [1], [2], [], [], []] 输出: [null, null, null, 1, 1, false] 解释: MyQueue myQueue = new MyQueue(); myQueue.push(1); // queue is: [1] myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue) myQueue.peek(); // return 1 myQueue.pop(); // return 1, queue is [2] myQueue.empty(); // return false
提示:
1 <= x <= 9 最多调用\(100\) 次\(\texttt{push}\) 、\(\texttt{pop}\) 、\(\texttt{peek}\) 和\(\texttt{empty}\) 假设所有操作都是有效的 (例如,一个空的队列不会调用\(\texttt{pop}\) 或者\(\texttt{peek}\) 操作) 进阶:
你能否实现每个操作均摊时间复杂度为 \(O(1)\) 的队列?换句话说,执行 \(n\) 个操作的总时间复杂度为 \(O(n)\) ,即使其中一个操作可能花费较长时间。
之前我们已经实现了 225. 用队列实现栈 ,今天我们来学习如何用队列来实现栈。
因为队列是FIFO ,而栈是LIFO ,所以我们需要用到两个栈,用其中一个来反转元素的入队顺序,而另一个则用来存储元素的最终顺序。
2个栈 (push - O(n), pop - O(1)) 使用 \(2\) 个栈 \(\textit{stack}_1\) 和 \(\textit{stack}_2\) ,\(\textit{stack}_1\) 作为主栈,而 \(\textit{stack}_2\) 是辅助栈。
入栈时:
把 \(\textit{stack}_1\) 中所有的元素移到 \(\textit{stack}_2\) 中; \(\textit{stack}_2\) 中压入新元素;把 \(\textit{stack}_2\) 中所有的元素弹出,再把弹出的元素压入 \(\textit{stack}_1\) 。 代码如下所示:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 class MyQueue { Stack<Integer> stack1; Stack<Integer> stack2; public MyQueue () { stack1 = new Stack <>(); stack2 = new Stack <>(); } public void push (int x) { if (stack1.empty()) { stack1.push(x); return ; } while (!stack1.empty()) { stack2.push(stack1.pop()); } stack2.push(x); while (!stack2.empty()) { stack1.push(stack2.pop()); } } public int pop () { return stack1.pop(); } public int peek () { return stack1.peek(); } public boolean empty () { return stack1.empty() && stack2.empty(); } }