用两个栈实现队列(尾插头删)

  描述:用两个栈实现一个队列。队列的声明如下,请实现它的两个函数appendTail和deletedHead,分别完成在队列尾部插入节点和在队列头部删除节点的功能。
  时间:2019-07-31 16:20
  类名:CQueue

分析
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

template <class T>
class CQueue
{
public:
	//CQueue();
	//~CQueue();
	void appendTail(const T& node);
	T deleteHead();
private:
	stack<T> stack1;
	stack<T> stack2;
};

template <class T>
void CQueue<T>::appendTail(const T& node)   //入队列,只从stack1入
{
	stack1.push(node);
}

template <class T>
T CQueue<T>::deleteHead()  
//当stack2不为空时,从stack1出,如果为空,则将stack1中的元素出战,压入stack2。
{
	if (stack2.size() <= 0)
	{
		if (stack1.size() <= 0)
			throw exception("the queue is empty");//两个栈都为空
		else
		{//stack1不为空,stack2为空,则stack1全部入stack2
			while (stack1.size() > 0)
			{
			    T value = stack1.top();
				stack2.push(value);
			    stack1.pop();
			}
		}
	}//stack2不为空则直接输出
	T r_value = stack2.top();
	stack2.pop();
	return r_value;
}

int main()
{
	CQueue<string> queue;
	queue.appendTail("a");
	queue.appendTail("b");
	queue.appendTail("c");

	cout <<queue.deleteHead() << endl;
	cout << queue.deleteHead() << endl;
	cout << queue.deleteHead() << endl;

	return 0;
}

在这里插入图片描述总结
  入队列的操作就等同于栈stack1.push()操作;
  栈stack1满并且栈stack2不为空时,队列满;
  出队列时首先要判断栈stack2是否为空,为空出队列,不为空则将栈stack1中的数据依次出到stack2中,然后再出队列;
  栈stack1和栈stack2都为空则队列空。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值