代码:
#include#include using namespace std;template class Cstack{public: Cstack(); ~Cstack(); void push(const T &element); T pop(); unsigned length();private: queue queue1; queue queue2;};template Cstack ::Cstack(){}template Cstack ::~Cstack(){}template void Cstack ::push(const T &element){ queue1.push(element);}template T Cstack ::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 unsigned Cstack ::length(){ return queue1.size() > queue2.size() ? queue1.size() : queue2.size();}int main(){ int a[] = { 1, 2, 3, 4, 5, 6 }; Cstack mystack; for (int i = 0; i < 6; i++){ mystack.push(a[i]); } while (mystack.length()>0) { cout << mystack.pop() << " "; } cout << endl; return 0;}