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!