兩個隊列實現棧

來源:互聯網
上載者:User

標籤:

用兩個隊列實現棧的功能.

 1 #include<iostream>  2 #include <deque>  3 using namespace std;  4 template<class T> class Mystack  5 {  6 public:  7     Mystack(){}  8     ~Mystack(){}  9     void push(T t); 10     T top(); 11     void pop(); 12 private: 13     deque<T> A; 14     deque<T> B; 15 }; 16 17 template<class T> void  Mystack<T>::push(T t)  //從隊列A尾部入棧18 { 19     A.push_back(t); 20 } 21 template<class T> T Mystack<T>::top() //B的頂部出棧22 { 23     while(A.size()>1) 24     { 25         B.push_back(A.front()); //A的頭部彈出進入B的尾部26         A.pop_front();  //對A的頭部進行清理工作27     } 28 29     T tmp=A.front();  //令temp指向A隊列頂部30     B.push_back(A.front());  //A的頂部進入B隊尾31 32     A.pop_front();  //對A的頭部進行清理工作33     while(B.size()!=0) 34     { 35         A.push_back(B.front()); //B的頭部彈出進入A的尾部36         B.pop_front(); 37     } 38     return tmp; 39 } 40 template<class T> void Mystack<T>::pop() 41 { 42     while(A.size()>1) 43     { 44         B.push_back(A.front()); 45         A.pop_front(); 46     } 47     A.pop_front(); 48     while(B.size()!=0) 49     { 50         A.push_back(B.front()); 51         B.pop_front(); 52     } 53 54 } 55 56 void main() 57 { 58     int i;59     Mystack<int> a; 60     for(i=0;i<10;i++) 61         a.push(i); 62     for(i=0;i<10;i++) 63     { 64         cout<<a.top()<<endl; 65         a.pop(); 66     } 67 }

 

兩個隊列實現棧

聯繫我們

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