两个栈实现一个队列

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值