#include <iostream>
#include <stack>
using namespace std;
template <typename T>
class Queue
{
public:
Queue() {};
~Queue() {};
void appendTail(const T &node);
T deleteHead();
private:
stack<T> stack1;
stack<T> stack2;
};
//新元素入栈,即加入队列
template <typename T>
void Queue<T>::appendTail(const T &node)
{
stack1.push(node);
cout <<node <<" now is in the queue!" <<endl;
}
//删除队列头部元素
template <typename T>
T Queue<T>::deleteHead()
{
//判断stack2是否为空。
//若为空没,则将stack1的元素依次压入stack2;若不为空,则先弹出stack2中的元素,再将stack1的元素压入stack2
if (stack2.size() <= 0)
{
while(stack1.size()>0)
{
T& data=stack1.top();
cout<<data <<endl;
stack2.push(data);
cout <<stack2.top() <<endl;
stack1.pop();//注意:应先把stack1的栈顶元素压入stack2,再将其pop。
}
}
if (stack2.size()==0)
{
throw exception("queue is empty!");
}
T &head=stack2.top();
cout <<head <<"now is output!" <<endl;
stack2.pop();
if (stack2.size()>0)
{
head=stack2.top();
cout<<"now the head is: "<<head <<endl;
}
else
head=-1;
return head;
}
int main()
{
Queue<int> cq;
cq.appendTail(1);
cq.appendTail(2);
cq.appendTail(3);
int head=cq.deleteHead();
head=cq.deleteHead();
head=cq.deleteHead();
return 0;
}