Implement Stack using Queues 用隊列實現棧

來源:互聯網
上載者:User

Implement the following operations of a stack using queues. push(x) -- Push element x onto stack. pop() -- Removes the element on top of the stack. top() -- Get the top element.

empty() -- Return whether the stack is empty. 解題思路: 用隊列實現棧的操作。包括輸入、輸出、取棧頂元素、判斷棧是否為空白。 我們知道,棧是先進後出的容器,隊列是先進先出的容器。所以輸入元素很簡單,但是輸出元素不是輸出隊列的front,而是back元素。刪掉back元素。此時我們可以將隊列1中的非隊尾元素存在另外一個隊列2中,刪掉之前隊列的最後一個元素不另行儲存就行。此時隊列2中有元素,是可執行檔容器,隊列1是空,備用容器,所以我們需要兩個表示符,代表兩個隊列,表示此隊列是否是當前可操作的容器。簡單來講,就是用兩個隊列的操作(push(),pop(),empty())來實現棧的各種操作。
完整可執行代碼如下:

#include<iostream>#include<queue>using namespace std;queue<int> qu1;queue<int> qu2;bool qu1_use=1;bool qu2_use=0;void push(int x);void pop() ;int top() ;bool empty() ;void main(){push(1);push(2);push(3);push(4);int i=5;while(i){if(!empty()){cout<<top()<<endl;pop();}i--;}}void push(int x){if(qu1_use==1){qu1.push(x);}elsequ2.push(x);}void pop() {if(qu1.empty()&&qu2.empty())exit(0);if(qu1_use==1&&!qu1.empty()){while(qu1.size()>1){qu2.push(qu1.front());    qu1.pop();}qu1.pop();qu1_use=0;qu2_use=1;return;}if(qu2_use==1&&!qu2.empty()){while(qu2.size()>1){qu1.push(qu2.front());    qu2.pop();}qu2.pop();qu1_use=1;qu2_use=0;return;}   return;}int top() {if(qu1_use==1&&!qu1.empty()){return qu1.back();}if(qu2_use==1&&!qu2.empty()){return qu2.back();}   //if(qu1.empty()&&qu2.empty())exit(0);    }bool empty() {if((qu1_use==1&&qu1.empty())||(qu2_use==1&&qu2.empty())){cout<<"empty!"<<endl;return true;}else return false;}

執行上面代碼得到結果為: 4 3 2 1 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.