pop操作:如果s2不为空,直接弹出s2的数据,否则依次弹出s1的数据到s2中,再取2栈顶的数据.
#include <iostream> #include <stack> using namespace std; template<typename T> class Queue { public: Queue() : qsize(0) { } void push(const int &t) { s1.push(t); ++ qsize; } T front(); void pop(); size_t size() { return qsize; } bool empty() { return qsize == 0; } private: size_t qsize; stack<int> s1; stack<int> s2; }; template<typename T> T Queue<T>::front() { if (s2.empty()) { if (s1.empty()) throw; while (!s1.empty()) { s2.push(s1.top()); s1.pop(); } } return s2.top(); } template<typename T> void Queue<T>::pop() { if (s2.empty()) { while (!s1.empty()) { s2.push(s1.top()); s1.pop(); } } if (!s2.empty()) { s2.pop(); } --qsize; } int main() { Queue<int> mq; for (int i = 0; i < 10; ++i) mq.push(i); while (!mq.empty()) { cout << mq.front() << endl; mq.pop(); } return 0; }
原文地址:http://blog.csdn.net/pegasuswang_/article/details/24782193