# 0232. 用棧實現隊列
## 題目地址(232. 用棧實現隊列)
<https://leetcode-cn.com/problems/implement-queue-using-stacks/>
## 題目描述
```
<pre class="calibre18">```
使用棧實現隊列的下列操作:
push(x) -- 將一個元素放入隊列的尾部。
pop() -- 從隊列首部移除元素。
peek() -- 返回隊列首部的元素。
empty() -- 返回隊列是否為空。
示例:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false
說明:
你只能使用標準的棧操作 -- 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
你所使用的語言也許不支持棧。你可以使用 list 或者 deque(雙端隊列)來模擬一個棧,只要是標準的棧操作即可。
假設所有操作都是有效的 (例如,一個空的隊列不會調用 pop 或者 peek 操作)。
```
```
## 前置知識
- [棧](https://github.com/azl397985856/leetcode/blob/master/thinkings/basic-data-structure.md)
## 公司
- 阿里
- 騰訊
- 百度
- 字節
- bloomberg
- microsoft
## 思路
這道題目是讓我們用棧來模擬實現隊列。 我們知道棧和隊列都是一種受限的數據結構。 棧的特點是只能在一端進行所有操作,隊列的特點是只能在一端入隊,另一端出隊。
在這里我們可以借助另外一個棧,也就是說用兩個棧來實現隊列的效果。這種做法的時間復雜度和空間復雜度都是O(n)。
由于棧只能操作一端,因此我們peek或者pop的時候也只去操作頂部元素,要達到目的 我們需要在push的時候將隊頭的元素放到棧頂即可。
因此我們只需要在push的時候,用一下輔助棧即可。 具體做法是先將棧清空并依次放到另一個輔助棧中,輔助棧中的元素再次放回棧中,最后將新的元素push進去即可。
比如我們現在棧中已經是1,2,3,4了。 我們現在要push一個5.
push之前是這樣的:

然后我們將棧中的元素轉移到輔助棧:

最后將新的元素添加到棧頂。

整個過程是這樣的:

## 關鍵點解析
- 在push的時候利用輔助棧(雙棧)
## 代碼
- 語言支持:JS, Python, Java
Javascript Code:
```
<pre class="calibre18">```
<span class="hljs-title">/*
* @lc app=leetcode id=232 lang=javascript
*
* [232] Implement Queue using Stacks
*/</span>
<span class="hljs-title">/**
* Initialize your data structure here.
*/</span>
<span class="hljs-keyword">var</span> MyQueue = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-title">// tag: queue stack array</span>
<span class="hljs-keyword">this</span>.stack = [];
<span class="hljs-keyword">this</span>.helperStack = [];
};
<span class="hljs-title">/**
* Push element x to the back of queue.
* @param {number} x
* @return {void}
*/</span>
MyQueue.prototype.push = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">x</span>) </span>{
<span class="hljs-keyword">let</span> cur = <span class="hljs-params">null</span>;
<span class="hljs-keyword">while</span> ((cur = <span class="hljs-keyword">this</span>.stack.pop())) {
<span class="hljs-keyword">this</span>.helperStack.push(cur);
}
<span class="hljs-keyword">this</span>.helperStack.push(x);
<span class="hljs-keyword">while</span> ((cur = <span class="hljs-keyword">this</span>.helperStack.pop())) {
<span class="hljs-keyword">this</span>.stack.push(cur);
}
};
<span class="hljs-title">/**
* Removes the element from in front of queue and returns that element.
* @return {number}
*/</span>
MyQueue.prototype.pop = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.stack.pop();
};
<span class="hljs-title">/**
* Get the front element.
* @return {number}
*/</span>
MyQueue.prototype.peek = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.stack[<span class="hljs-keyword">this</span>.stack.length - <span class="hljs-params">1</span>];
};
<span class="hljs-title">/**
* Returns whether the queue is empty.
* @return {boolean}
*/</span>
MyQueue.prototype.empty = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.stack.length === <span class="hljs-params">0</span>;
};
<span class="hljs-title">/**
* Your MyQueue object will be instantiated and called as such:
* var obj = new MyQueue()
* obj.push(x)
* var param_2 = obj.pop()
* var param_3 = obj.peek()
* var param_4 = obj.empty()
*/</span>
```
```
Python Code:
```
<pre class="calibre18">```
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyQueue</span>:</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self)</span>:</span>
<span class="hljs-string">"""
Initialize your data structure here.
"""</span>
self.stack = []
self.help_stack = []
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">push</span><span class="hljs-params">(self, x: int)</span> -> <span class="hljs-keyword">None</span>:</span>
<span class="hljs-string">"""
Push element x to the back of queue.
"""</span>
<span class="hljs-keyword">while</span> self.stack:
self.help_stack.append(self.stack.pop())
self.help_stack.append(x)
<span class="hljs-keyword">while</span> self.help_stack:
self.stack.append(self.help_stack.pop())
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">pop</span><span class="hljs-params">(self)</span> -> int:</span>
<span class="hljs-string">"""
Removes the element from in front of queue and returns that element.
"""</span>
<span class="hljs-keyword">return</span> self.stack.pop()
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">peek</span><span class="hljs-params">(self)</span> -> int:</span>
<span class="hljs-string">"""
Get the front element.
"""</span>
<span class="hljs-keyword">return</span> self.stack[<span class="hljs-params">-1</span>]
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">empty</span><span class="hljs-params">(self)</span> -> bool:</span>
<span class="hljs-string">"""
Returns whether the queue is empty.
"""</span>
<span class="hljs-keyword">return</span> <span class="hljs-keyword">not</span> bool(self.stack)
<span class="hljs-title"># Your MyQueue object will be instantiated and called as such:</span>
<span class="hljs-title"># obj = MyQueue()</span>
<span class="hljs-title"># obj.push(x)</span>
<span class="hljs-title"># param_2 = obj.pop()</span>
<span class="hljs-title"># param_3 = obj.peek()</span>
<span class="hljs-title"># param_4 = obj.empty()</span>
```
```
Java Code
```
<pre class="calibre18">```
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyQueue</span> </span>{
Stack<Integer> pushStack = <span class="hljs-keyword">new</span> Stack<> ();
Stack<Integer> popStack = <span class="hljs-keyword">new</span> Stack<> ();
<span class="hljs-title">/** Initialize your data structure here. */</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">MyQueue</span><span class="hljs-params">()</span> </span>{
}
<span class="hljs-title">/** Push element x to the back of queue. */</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">push</span><span class="hljs-params">(<span class="hljs-keyword">int</span> x)</span> </span>{
<span class="hljs-keyword">while</span> (!popStack.isEmpty()) {
pushStack.push(popStack.pop());
}
pushStack.push(x);
}
<span class="hljs-title">/** Removes the element from in front of queue and returns that element. */</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">pop</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">while</span> (!pushStack.isEmpty()) {
popStack.push(pushStack.pop());
}
<span class="hljs-keyword">return</span> popStack.pop();
}
<span class="hljs-title">/** Get the front element. */</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">peek</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">while</span> (!pushStack.isEmpty()) {
popStack.push(pushStack.pop());
}
<span class="hljs-keyword">return</span> popStack.peek();
}
<span class="hljs-title">/** Returns whether the queue is empty. */</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">empty</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> pushStack.isEmpty() && popStack.isEmpty();
}
}
<span class="hljs-title">/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/</span>
`
```
```
**復雜度分析**
- 時間復雜度:O(1)O(1)O(1)
- 空間復雜度:O(1)O(1)O(1)
## 擴展
- 類似的題目有用隊列實現棧,思路是完全一樣的,大家有興趣可以試一下。
- 棧混洗也是借助另外一個棧來完成的,從這點來看,兩者有相似之處。
## 延伸閱讀
實際上現實中也有使用兩個棧來實現隊列的情況,那么為什么我們要用兩個stack來實現一個queue?
其實使用兩個棧來替代一個隊列的實現是為了在多進程中分開對同一個隊列對讀寫操作。一個棧是用來讀的,另一個是用來寫的。當且僅當讀棧滿時或者寫棧為空時,讀寫操作才會發生沖突。
當只有一個線程對棧進行讀寫操作的時候,總有一個棧是空的。在多線程應用中,如果我們只有一個隊列,為了線程安全,我們在讀或者寫隊列的時候都需要鎖住整個隊列。而在兩個棧的實現中,只要寫入棧不為空,那么`push`操作的鎖就不會影響到`pop`。
- [reference](https://leetcode.com/problems/implement-queue-using-stacks/discuss/64284/Do-you-know-when-we-should-use-two-stacks-to-implement-a-queue)
- [further reading](https://stackoverflow.com/questions/2050120/why-use-two-stacks-to-make-a-queue/2050402#2050402)
更多題解可以訪問我的LeetCode題解倉庫:<https://github.com/azl397985856/leetcode> 。 目前已經37K star啦。
關注公眾號力扣加加,努力用清晰直白的語言還原解題思路,并且有大量圖解,手把手教你識別套路,高效刷題。

- Introduction
- 第一章 - 算法專題
- 數據結構
- 基礎算法
- 二叉樹的遍歷
- 動態規劃
- 哈夫曼編碼和游程編碼
- 布隆過濾器
- 字符串問題
- 前綴樹專題
- 《貪婪策略》專題
- 《深度優先遍歷》專題
- 滑動窗口(思路 + 模板)
- 位運算
- 設計題
- 小島問題
- 最大公約數
- 并查集
- 前綴和
- 平衡二叉樹專題
- 第二章 - 91 天學算法
- 第一期講義-二分法
- 第一期講義-雙指針
- 第二期
- 第三章 - 精選題解
- 《日程安排》專題
- 《構造二叉樹》專題
- 字典序列刪除
- 百度的算法面試題 * 祖瑪游戲
- 西法的刷題秘籍】一次搞定前綴和
- 字節跳動的算法面試題是什么難度?
- 字節跳動的算法面試題是什么難度?(第二彈)
- 《我是你的媽媽呀》 * 第一期
- 一文帶你看懂二叉樹的序列化
- 穿上衣服我就不認識你了?來聊聊最長上升子序列
- 你的衣服我扒了 * 《最長公共子序列》
- 一文看懂《最大子序列和問題》
- 第四章 - 高頻考題(簡單)
- 面試題 17.12. BiNode
- 0001. 兩數之和
- 0020. 有效的括號
- 0021. 合并兩個有序鏈表
- 0026. 刪除排序數組中的重復項
- 0053. 最大子序和
- 0088. 合并兩個有序數組
- 0101. 對稱二叉樹
- 0104. 二叉樹的最大深度
- 0108. 將有序數組轉換為二叉搜索樹
- 0121. 買賣股票的最佳時機
- 0122. 買賣股票的最佳時機 II
- 0125. 驗證回文串
- 0136. 只出現一次的數字
- 0155. 最小棧
- 0167. 兩數之和 II * 輸入有序數組
- 0169. 多數元素
- 0172. 階乘后的零
- 0190. 顛倒二進制位
- 0191. 位1的個數
- 0198. 打家劫舍
- 0203. 移除鏈表元素
- 0206. 反轉鏈表
- 0219. 存在重復元素 II
- 0226. 翻轉二叉樹
- 0232. 用棧實現隊列
- 0263. 丑數
- 0283. 移動零
- 0342. 4的冪
- 0349. 兩個數組的交集
- 0371. 兩整數之和
- 0437. 路徑總和 III
- 0455. 分發餅干
- 0575. 分糖果
- 0874. 模擬行走機器人
- 1260. 二維網格遷移
- 1332. 刪除回文子序列
- 第五章 - 高頻考題(中等)
- 0002. 兩數相加
- 0003. 無重復字符的最長子串
- 0005. 最長回文子串
- 0011. 盛最多水的容器
- 0015. 三數之和
- 0017. 電話號碼的字母組合
- 0019. 刪除鏈表的倒數第N個節點
- 0022. 括號生成
- 0024. 兩兩交換鏈表中的節點
- 0029. 兩數相除
- 0031. 下一個排列
- 0033. 搜索旋轉排序數組
- 0039. 組合總和
- 0040. 組合總和 II
- 0046. 全排列
- 0047. 全排列 II
- 0048. 旋轉圖像
- 0049. 字母異位詞分組
- 0050. Pow(x, n)
- 0055. 跳躍游戲
- 0056. 合并區間
- 0060. 第k個排列
- 0062. 不同路徑
- 0073. 矩陣置零
- 0075. 顏色分類
- 0078. 子集
- 0079. 單詞搜索
- 0080. 刪除排序數組中的重復項 II
- 0086. 分隔鏈表
- 0090. 子集 II
- 0091. 解碼方法
- 0092. 反轉鏈表 II
- 0094. 二叉樹的中序遍歷
- 0095. 不同的二叉搜索樹 II
- 0096. 不同的二叉搜索樹
- 0098. 驗證二叉搜索樹
- 0102. 二叉樹的層序遍歷
- 0103. 二叉樹的鋸齒形層次遍歷
- 105. 從前序與中序遍歷序列構造二叉樹
- 0113. 路徑總和 II
- 0129. 求根到葉子節點數字之和
- 0130. 被圍繞的區域
- 0131. 分割回文串
- 0139. 單詞拆分
- 0144. 二叉樹的前序遍歷
- 0150. 逆波蘭表達式求值
- 0152. 乘積最大子數組
- 0199. 二叉樹的右視圖
- 0200. 島嶼數量
- 0201. 數字范圍按位與
- 0208. 實現 Trie (前綴樹)
- 0209. 長度最小的子數組
- 0211. 添加與搜索單詞 * 數據結構設計
- 0215. 數組中的第K個最大元素
- 0221. 最大正方形
- 0229. 求眾數 II
- 0230. 二叉搜索樹中第K小的元素
- 0236. 二叉樹的最近公共祖先
- 0238. 除自身以外數組的乘積
- 0240. 搜索二維矩陣 II
- 0279. 完全平方數
- 0309. 最佳買賣股票時機含冷凍期
- 0322. 零錢兌換
- 0328. 奇偶鏈表
- 0334. 遞增的三元子序列
- 0337. 打家劫舍 III
- 0343. 整數拆分
- 0365. 水壺問題
- 0378. 有序矩陣中第K小的元素
- 0380. 常數時間插入、刪除和獲取隨機元素
- 0416. 分割等和子集
- 0445. 兩數相加 II
- 0454. 四數相加 II
- 0494. 目標和
- 0516. 最長回文子序列
- 0518. 零錢兌換 II
- 0547. 朋友圈
- 0560. 和為K的子數組
- 0609. 在系統中查找重復文件
- 0611. 有效三角形的個數
- 0718. 最長重復子數組
- 0754. 到達終點數字
- 0785. 判斷二分圖
- 0820. 單詞的壓縮編碼
- 0875. 愛吃香蕉的珂珂
- 0877. 石子游戲
- 0886. 可能的二分法
- 0900. RLE 迭代器
- 0912. 排序數組
- 0935. 騎士撥號器
- 1011. 在 D 天內送達包裹的能力
- 1014. 最佳觀光組合
- 1015. 可被 K 整除的最小整數
- 1019. 鏈表中的下一個更大節點
- 1020. 飛地的數量
- 1023. 駝峰式匹配
- 1031. 兩個非重疊子數組的最大和
- 1104. 二叉樹尋路
- 1131.絕對值表達式的最大值
- 1186. 刪除一次得到子數組最大和
- 1218. 最長定差子序列
- 1227. 飛機座位分配概率
- 1261. 在受污染的二叉樹中查找元素
- 1262. 可被三整除的最大和
- 1297. 子串的最大出現次數
- 1310. 子數組異或查詢
- 1334. 閾值距離內鄰居最少的城市
- 1371.每個元音包含偶數次的最長子字符串
- 第六章 - 高頻考題(困難)
- 0004. 尋找兩個正序數組的中位數
- 0023. 合并K個升序鏈表
- 0025. K 個一組翻轉鏈表
- 0030. 串聯所有單詞的子串
- 0032. 最長有效括號
- 0042. 接雨水
- 0052. N皇后 II
- 0084. 柱狀圖中最大的矩形
- 0085. 最大矩形
- 0124. 二叉樹中的最大路徑和
- 0128. 最長連續序列
- 0145. 二叉樹的后序遍歷
- 0212. 單詞搜索 II
- 0239. 滑動窗口最大值
- 0295. 數據流的中位數
- 0301. 刪除無效的括號
- 0312. 戳氣球
- 0335. 路徑交叉
- 0460. LFU緩存
- 0472. 連接詞
- 0488. 祖瑪游戲
- 0493. 翻轉對
- 0887. 雞蛋掉落
- 0895. 最大頻率棧
- 1032. 字符流
- 1168. 水資源分配優化
- 1449. 數位成本和為目標值的最大數字
- 后序