用兩個棧實現隊列

來源:互聯網
上載者:User

標籤:

用兩個棧實現隊列
  • 參與人數:3047時間限制:1秒空間限制:32768K
  • 通過比例:34.71%
  • 最佳記錄:0 ms|0K(來自  青哥)
題目描述用兩個棧來實現一個隊列,完成隊列的Push和Pop操作。 隊列中的元素為int類型。


  思路1(最普通的方法):
  1、入隊時,直接壓入到stack1中;
  2、出隊時,先將stack1中的所有size-1個元素壓入stack2中,然後將stack1的元素彈出;最後將stack2中的元素重新壓入到s1中。

  如所示:

 1 class Solution 2 { 3 public: 4     void push(int node) { 5         stack1.push(node); 6     } 7  8     int pop() { 9         int t;10         while (stack1.size() > 1){11             t = stack1.top();12             stack2.push(t);13             stack1.pop();14         }15         int rt = stack1.top();16         stack1.pop();17         while(stack2.size() > 0){18             t = stack2.top();19             stack1.push(t);20             stack2.pop();21         }22         return rt;23     }24 25 private:26     stack<int> stack1;27     stack<int> stack2;28 };
View Code

 

 

  思路2(最佳化):

  1、入隊時,直接壓入到stack1中;
  2、出隊時,若stack2不為空白,則直接彈出;若stack2為空白,則將stack1的size-1個元素壓入stack2中,最後彈出stack1中的棧頂元素。

 1 class Solution 2 { 3 public: 4     void push(int node) { 5         stack1.push(node); 6     } 7  8     int pop() { 9         int rt;10         if (!stack2.empty()){11             rt = stack2.top();12             stack2.pop();13         }14         else{15             while (stack1.size() > 1){16                 rt = stack1.top();17                 stack2.push(rt);18                 stack1.pop();19             }20             rt = stack1.top();21             stack1.pop();22         }23         return rt;24     }25 private:26     stack<int> stack1;27     stack<int> stack2;28 };
View Code

 

 

 

 

用兩個棧實現隊列

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.