题目:用两个栈实现队列,队列有两个函数,appendTail和deleteHead,分别完成在队尾添加数据和出队头。
#include <iostream>
#include <stack>
#include <exception>
using namespace std;
template<class T>
class CQueue
{
public:
CQueue() {}
~CQueue() {}
void appendTail(const T& node)
{
stack1.push(node);
}
T deleteHead()
{
if(stack2.size()<= 0)
{
while(stack1.size()>0)
{
T& data = stack1.top();
stack1.pop();
stack2.push(data);
}
}
if(stack2.size() == 0)
{
cout << "queue is empty" << endl;
return NULL;
//throw new exception("queue is empty");
}
T head = stack2.top();
stack2.pop();
return head;
}
private:
stack<T> stack1;
stack<T> stack2;
};
int main()
{
CQueue<int> q;
q.appendTail(1);
q.appendTail(2);
q.appendTail(3);
cout << q.deleteHead() << endl;
q.appendTail(3);
cout << q.deleteHead() << endl;
cout << q.deleteHead() << endl;
cout << q.deleteHead() << endl;
return 0;
}