兩個隊列類比一個棧,兩個隊列類比
#include <iostream> #include <assert.h> #include <queue> using namespace std; /*兩個隊列類比一個堆棧*/ /*隊列A、B 入棧:將元素依次壓入到非空的隊列,第一個元素壓倒對列A 出棧:把隊列A的前n-1個元素倒到隊列B,把第n個元素去掉。此時資料在B中,下次操作,則對B操作。 棧頂:把隊列A的前n-1個元素倒到隊列B,把第n個元素作為棧頂*/ template <typename T> class MyStack { public: //入棧,第一個元素進到隊列deque1,以後每個元素進到非空的隊列 void push(const T &element) ; //出棧,將非空隊列的前n-1個元素轉移到另一個空的隊列,刪除非空隊列的第n個元素 void pop() ; //棧頂元素,將非空隊列的前n-1個元素轉移到另一個空的隊列,將非空隊列的第n個元素返回 T top(); //棧是否為空白 bool empty() { return (q1.empty()&&q2.empty()); } private: queue<T> q1; queue<T> q2; }; template<typename T> void MyStack<T>::push(const T &element){ if (q1.empty() && q2.empty()) { q1.push(element); } else if (!q1.empty() && q2.empty()) { q1.push(element); } else if (q1.empty() && !q2.empty()) { q2.push(element); } } template<typename T>void MyStack<T>::pop(){ if (!q1.empty()) { int size = q1.size(); for (int i=0; i<size-1; i++) { q2.push(q1.front()); q1.pop(); } q1.pop(); } else { int size = q2.size(); for (int i=0; i<size-1; i++) { q1.push(q2.front()); q2.pop(); } q2.pop(); } } template <typename T>T MyStack<T>::top(){ if (!q1.empty()) { int size = q1.size(); for (int i=0; i<size-1; i++) { q2.push(q1.front()); q1.pop(); } T temp = q1.front(); q1.pop(); q2.push(temp); return temp; } else { int size = q2.size(); for (int i=0; i<size-1; i++) { q1.push(q2.front()); q2.pop(); } T temp = q2.front(); q2.pop(); q1.push(temp); return temp; } } int main(int argc, char *argv[]) { MyStack<int> my; for (int i=0; i<10; i++) { my.push(i); } while (!my.empty()) { cout<<my.top()<<" "; my.pop(); } cout<<endl; return 0;}