代码:
#include<iostream> #include<queue> using namespace std; template<class T> class Cstack { public: Cstack(); ~Cstack(); void push(const T &element); T pop(); unsigned length(); private: queue<T> queue1; queue<T> queue2; }; template<class T> Cstack<T>::Cstack(){} template<class T> Cstack<T>::~Cstack(){} template<class T> void Cstack<T>::push(const T &element) { queue1.push(element); } template<class T> T Cstack<T>::pop() { if (queue1.size() > 0 || queue2.size() > 0) { if (queue2.size() <= 0) { while (queue1.size()>1) { T &data = queue1.front(); queue1.pop(); queue2.push(data); } T res = queue1.front(); queue1.pop(); return res; } else { while (queue2.size()>1) { T &data = queue2.front(); queue2.pop(); queue1.push(data); } T res = queue2.front(); queue2.pop(); return res; } } else { throw exception("stack is empty!"); } } template<class T> unsigned Cstack<T>::length() { return queue1.size() > queue2.size() ? queue1.size() : queue2.size(); } int main() { int a[] = { 1, 2, 3, 4, 5, 6 }; Cstack<int> mystack; for (int i = 0; i < 6; i++){ mystack.push(a[i]); } while (mystack.length()>0) { cout << mystack.pop() << " "; } cout << endl; return 0; }