代码示例:
#include<iostream>
#include<stack>
#include <exception>
using namespace std;
template<typename T>
class CQueue
{
public:
CQueue(void)
{
}
~CQueue(void)
{
}
void appendTail(const T&node);
T deleteHead(void);
private:
stack<T> stack1;
stack<T> stack2;
};
template<typename T>
void CQueue<T>::appendTail(const T &node)
{
stack1.push(node);
}
template<typename T>
T CQueue<T>::deleteHead(void)
{
T returndata;
if (stack2.empty())
{
while (!stack1.empty())
{
T temp = stack1.top();
stack1.pop();
stack2.push(temp);
}
if (stack2.empty())
{
throw exception("queue is empty");
}
}
//
if (!stack2.empty())
{
returndata = stack2.top();
stack2.pop();
return returndata;
}
}
void main()
{
CQueue<int> mycqueue;
int a[1] = { 4};
for (int i = 0; i < 1; i++)
{
mycqueue.appendTail(a[i]);
}
//===
cout << "第一次删除队首元素:";
try{
int res = mycqueue.deleteHead();
cout << res << endl;
}
catch (exception &e)
{
cout << e.what() << endl;
}
//===
cout << "第二次删除队首元素:";
try{
int res = mycqueue.deleteHead();
cout << res << endl;
}
catch (exception &e)
{
cout << e.what() << endl;
}
}