<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                企業??AI智能體構建引擎,智能編排和調試,一鍵部署,支持知識庫和私有化部署方案 廣告
                # 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之前是這樣的: ![](https://img.kancloud.cn/1c/81/1c8161f262fca7ae9530a82591d9a823_434x223.jpg) 然后我們將棧中的元素轉移到輔助棧: ![](https://img.kancloud.cn/1d/96/1d9608bc6cc17ba6fed5fcf94ece4acb_313x264.jpg) 最后將新的元素添加到棧頂。 ![](https://img.kancloud.cn/bc/ed/bced05dbd68c75cbf7b23e1f42284611_353x252.jpg) 整個過程是這樣的: ![](https://img.kancloud.cn/3a/35/3a35b3010dc9e00945cd052e33d8284e_700x467.jpg) ## 關鍵點解析 - 在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啦。 關注公眾號力扣加加,努力用清晰直白的語言還原解題思路,并且有大量圖解,手把手教你識別套路,高效刷題。 ![](https://img.kancloud.cn/cf/0f/cf0fc0dd21e94b443dd8bca6cc15b34b_900x500.jpg)
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看