#include <iostream>
#include <stack>
using namespace std;
template<typename T>
class QUEUE
{
public:
QUEUE(){}
~QUEUE(){}
void APPEND(const T val)
{
while(st2.empty()==false)
{
//我們只用st2保存數據,st1作爲中間交換橋樑。
//首先將st2中的數據逆序保存在st1中。
st1.push(st2.top());
st2.pop();
}
//然後將輸入的值放在st1得頂部。
st1.push(val);
while(st1.empty()==false)
{
//此刻再將st1中的數據全部放到st2中,
//恰恰保證了剛纔的新val是在底部,實現了
//隊列先進後出的思想。
st2.push(st1.top());
st1.pop();
}
}
int DELHED()
{
int temp = st2.top();
st2.pop();
return temp;
}
void Printf()
{
stack<int> st3 = st2;
//打印的話,爲了不影響原來的棧,選擇使用了一個臨時變量。
while(st3.empty()==false)
{
cout<<st3.top()<<" ";
st3.pop();
}
cout<<endl;
}
private:
stack<T> st1;
stack<T> st2;
};
int main()
{
QUEUE<int> qe;
for(int i=0;i<10;i++)
{
qe.APPEND(i);
}
qe.Printf();
qe.DELHED();
qe.Printf();
qe.DELHED();
qe.Printf();
qe.DELHED();
qe.Printf();
qe.DELHED();
qe.Printf();
qe.DELHED();
qe.Printf();
qe.DELHED();
qe.Printf();
qe.DELHED();
qe.Printf();
return 0;
}
筆試題:用兩個棧實現隊列
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.