思路分析:一個爲插入棧,另外一個爲彈出棧,能夠認爲插入站提供入隊列的功能,彈出棧提供出隊列的功能。若是彈出棧不爲空,則直接彈出它的數據。若是彈出棧爲空,則依次彈出插入棧的數據,放入彈出棧中,再彈出它的數據。ios
代碼以下:spa
#include "stdafx.h" #include <iostream> #include <stack> using namespace std; template <typename T> class QueueByDoubleStack { public: size_t size(); bool empty(); void push(T t); void pop(); T top(); private: stack<T> s1; stack<T> s2; }; template <typename T> size_t QueueByDoubleStack<T>::size() { return s1.size() + s2.size(); } template <typename T> bool QueueByDoubleStack<T>::empty() { return s1.empty() && s2.empty(); } template <typename T> void QueueByDoubleStack<T>::push(T t) { s1.push(t); } template <typename T> void QueueByDoubleStack<T>::pop() { if (s2.empty()) { while (!s1.empty()) { s2.push(s1.top()); s1.pop(); } } s2.pop(); } template <typename T> T QueueByDoubleStack<T>::top() { if (s2.empty()) { while (!s1.empty()) { s2.push(s1.top()); s1.top(); } } return s2.top(); } int main() { QueueByDoubleStack<int> q; for (int i = 0; i < 10; i++) { q.push(i); } while (!q.empty()) { cout << q.top() << ' '; q.pop(); } cout << endl; getchar(); return 0; }