#include <iostream> #include <stack> #include <stdlib.h> using namespace std; //唉,模板都忘的差不多了,就写个整型的吧 class MyQueue{ private: stack<int> s1; stack<int> s2; public: void enqueue(const int &n){ s1.push(n); } int size() { return (s1.size()+s2.size()); } int dequeue(){ if(s2.size()<=0){ while(s1.size()>0){ int& temp=s1.top(); s1.pop(); s2.push(temp); } } if(s2.size()==0){ cout<<"Queue is empty"<<endl; exit(1); } int n=s2.top(); s2.pop(); return n; } }; int main(){ MyQueue q; for(int i=0;i<10;i++){ q.enqueue(i); } cout<<"size="<<q.size()<<endl; cout<<q.dequeue()<<endl; cout<<"size="<<q.size()<<endl; q.enqueue(20); cout<<"size="<<q.size()<<endl; while(q.size()>0){ cout<<"size="<<q.size()<<endl; cout<<q.dequeue()<<endl; } return 0; }
原文地址:http://blog.csdn.net/dutsoft/article/details/26480265