用兩個隊列實現一個棧

題目:用兩個隊列實現一個棧


代碼:

#include <iostream>
#include <deque>
using namespace std;


template<class T> class Mystack
{
public:
Mystack(){};
~Mystack(){};
void push(T t);
T top();
void pop();


private:
deque<T> A;
deque<T> B;
};   //類聲明結束


template<class T> void Mystack<T>::push(T t) //入棧
{
A.push_back(t);
}

template<class T> T Mystack<T>::top()  //提取棧頂元素
{
T tmp = A.back();
return tmp;
}


template<class T> void Mystack<T>::pop() //出棧
{
while (A.size() > 1)
{
B.push_back(A.front());
A.pop_front();
}
A.pop_front();
while (B.size() != 0)
{
A.push_back(B.front());
B.pop_front();
}
}


void main()     
{
Mystack<int> a;
for (int i = 0; i < 5; i++)
{
a.push(i);
}
for (int i = 0; i < 5; i++)
{
cout << a.top() << endl;
a.pop();
}
}

運行結果如下圖所示:


注:top()函數有另外一個版本,不過比較麻煩,具體代碼如下:

template<class T> T Mystack<T>::top()
{
while (A.size() > 1)  //將隊列A中的size()-1個元素入隊列B,隊列A中只留下一個元素
{
B.push_back(A.front());
A.pop_front();
}


T tmp = A.front();     //取隊列A隊首元素,即棧的棧頂元素
B.push_back(A.front());  
A.pop_front();


while (B.size() != 0)
{
A.push_back(B.front());
B.pop_front();
}
return tmp; //tmp即棧頂元素
}  


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章