LeetCode 225. Implement Stack using Queues

來源:互聯網
上載者:User

標籤:

用queue類比stack,因為queue只能取front的值,和stack正好相反,因此核心思想是queue保持著與stack相反的順序,一直逆序,所以每次push進一個新值後,要依次把新值之前的值排到隊尾。比如原來q為4、5,push進1,q依次為:4、5、1;5、1、4;1、4、5. 對應的stack最終值為:5、4、1.

 1 class Stack { 2 public: 3     // Push element x onto stack. 4     void push(int x) { 5         int size = q.size(); 6         q.push(x); 7         for(int i = 0; i < size; ++i){ 8             int tmp = q.front(); 9             q.pop();10             q.push(tmp);11         }12     }13 14     // Removes the element on top of the stack.15     void pop() {16         q.pop();17     }18 19     // Get the top element.20     int top() {21         return q.front();22     }23 24     // Return whether the stack is empty.25     bool empty() {26         return q.empty();27     }28 private:29     queue<int> q;30 };

 

LeetCode 225. Implement Stack using Queues

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.