leetcode 225 Implement Stack using Queues,leetcodequeues

來源:互聯網
上載者:User

leetcode 225 Implement Stack using Queues,leetcodequeues
1. 問題描述

  用隊列來類比棧的操作。實現如下棧操作:
  

  • push(x) 將元素x入棧。
  • pop() 出棧。
  • top() 擷取棧頂元素。
  • empty() 判斷是否為空白。

  注意:只能用隊列的標準操作,隊頭取元素,隊尾插入元素,擷取隊列的大小,以及隊列是否為空白。

2 方法和思路

  可以用兩個隊列q1和q2來實現棧的操作,設q2為輔助隊列。
  

  • 入棧時將元素都存入q1隊列中。
  • 出棧時將q1中前n-1個元素放入q2隊列,然後pop出q1的最後一個元素,最後將q2隊列中的元素在放回到q1中。
  • 擷取棧頂元素思路類似,只不過q1最後一個元素返回後,將其入q2,然後再將q2中所有元素放回到q1隊列中,恢複原樣。
  • 判斷棧是否為空白直接判斷q1隊列是否為空白即可。

      C++代碼如下:
      

class Stack {    private:    queue<int> q1;    queue<int> q2;public:    // Push element x onto stack.    void push(int x) {        q1.push(x);    }    // Removes the element on top of the stack.    void pop() {        int n = q1.size();        for(int i = 0; i < n -1; i++)        {            q2.push(q1.front());            q1.pop();        }        q1.pop();        while(!q2.empty())        {            q1.push(q2.front());            q2.pop();        }                 }    // Get the top element.    int top() {        int re,n = q1.size();        for(int i = 0; i < n -1; i++)        {            q2.push(q1.front());            q1.pop();        }        re = q1.front();        q2.push(q1.front());        q1.pop();        while(!q2.empty())        {            q1.push(q2.front());            q2.pop();        }               return re;    }    // Return whether the stack is empty.    bool empty() {        return q1.empty();    }};

聯繫我們

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