//用兩個棧實現隊列,實現在隊尾添加元素和在隊列頭部刪除元素
#include <iostream>
using namespace std;
const int DEPTH = 20; //定義棧的深度
template <class T> struct stack //定義棧模版
{
int top; //棧頂指針
T S[DEPTH]; //定義一個數組存儲棧中數據
bool push(T member)
{
if (top >= 20)
{
throw ("棧已滿!");
}
S[top] = member;
top++;
}
T pop()
{
if (0 >= top)
{
throw ("棧爲空!");
}
top--;
return S[top];
}
};
template <class T> class CQueue //定義隊列模版
{
public:
CQueue(void);
~CQueue(void);
void appendTail(const T& node); //隊尾添加元素
T deleteHead(); //隊頭刪除元素
private:
stack<T> stack1;
stack<T> stack2;
};
template <class T>
CQueue<T>::CQueue(void)
{
stack1.top = 0;
stack2.top = 0;
}
template <class T>
CQueue<T>::~CQueue(void)
{
}
template <class T>
void CQueue<T>::appendTail(const T& node)
{
try
{
stack1.push(node);
}
catch(char *e)
{
cout << "隊列已滿!" << endl;
}
}
template <class T>
T CQueue<T>::deleteHead()
{
int size2 = stack2.top; //stack1中的元素個數
if (size2 == 0)
{
int temp = stack1.top;
if (temp == 0)
{
throw ("隊列已空!");
}
for (int i=0; i<temp; i++)
{
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
int main()
{
CQueue<int> que;
try
{
for (int i=0; i<21; i++)
{
que.appendTail(i);
}
for (int i=0; i<21; i++)
{
cout << que.deleteHead() << " ";
}
}
catch (char *e)
{
cout << e << endl;
}
return 0;
}
用兩個棧實現隊列
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.