思路:設置兩個棧stack1和stack2,stack1實現入隊列功能,stack2實現出隊列功能。
(1)入隊列:入棧stack1
(2)出隊列:若stack2不空,則直接彈出stack2中的棧頂元素
若stack2為空,則依次彈出stack1中的元素放入stack2中,再彈出stack2中的棧頂元素
C++代碼:
#include "stdafx.h" #include <iostream> #include <stack> using namespace std; template<class T> class CQueue { public: CQueue(void); ~CQueue(void); void AddTail(const T &addData); void DeleteHead(T &deleteData); private: stack<T> stack1; stack<T> stack2; }; template<class T> CQueue<T>::CQueue(void) { } template<class T> CQueue<T>::~CQueue(void) { } template<class T> void CQueue<T>::AddTail(const T &addData) { stack1.push(addData); } template<class T> void CQueue<T>::DeleteHead(T &deleteData) { if (stack2.empty()) { while (!stack1.empty()) { T topData = stack1.top(); stack2.push(topData); stack1.pop(); } } if (stack2.empty()) { cout << "隊列中無元素!" << endl; } else { deleteData = stack2.top(); stack2.pop(); } } int _tmain(int argc, _TCHAR* argv[]) { CQueue<int> q; for (int i=0; i<6; i++) { q.AddTail(i); } int deleteData = 0; for (int i=0; i<6; i++) { q.DeleteHead(deleteData); cout << deleteData << " "; } cout << endl; q.DeleteHead(deleteData); system("pause"); return 0; } #include "stdafx.h" #include <iostream> #include <stack> using namespace std; template<class T> class CQueue { public: CQueue(void); ~CQueue(void); void AddTail(const T &addData); void DeleteHead(T &deleteData); private: stack<T> stack1; stack<T> stack2; }; template<class T> CQueue<T>::CQueue(void) { } template<class T> CQueue<T>::~CQueue(void) { } template<class T> void CQueue<T>::AddTail(const T &addData) { stack1.push(addData); } template<class T> void CQueue<T>::DeleteHead(T &deleteData) { if (stack2.empty()) { while (!stack1.empty()) { T topData = stack1.top(); stack2.push(topData); stack1.pop(); } } if (stack2.empty()) { cout << "隊列中無元素!" << endl; } else { deleteData = stack2.top(); stack2.pop(); } } int _tmain(int argc, _TCHAR* argv[]) { CQueue<int> q; for (int i=0; i<6; i++) { q.AddTail(i); } int deleteData = 0; for (int i=0; i<6; i++) { q.DeleteHead(deleteData); cout << deleteData << " "; } cout << endl; q.DeleteHead(deleteData); system("pause"); return 0; }