c++ 两个队列实现栈

准备两个队列,一个主队列,一个辅助队列。入队时,仅主队列入队。出队时先循环把主队列的元素(留最最后一个)转移到辅助队列里,剩下的最后一个就是要弹出的数据。然后把主队列和辅助队列的地址互换。


/*==============================================================*
 *   Copyright (C) All rights reserved.
 *   
 *   文件名称:
 *   创 建 者:徐永琪
 *   创建日期:2022年04月01日
 *   描    述:两个队列实现栈
 *
 ================================================================*/
#include <queue>
#include <iostream>
/*by xuyongqi*/

using namespace std;

class two_queues_implement_stack
{
private:
	queue<int> _queue;
	queue<int> _help;
public:
	void push(int data);
	void pop();
	int top();
	bool empty();
};

void two_queues_implement_stack::push(int data)
{
	_queue.push(data);
}

void two_queues_implement_stack::pop()
{
	while (_queue.size()>1)
	{
		_help.push(_queue.front());
		_queue.pop();

	}
	_queue.pop();
	queue<int> temp = _queue;
	_queue = _help;
	_help = temp;
}

int two_queues_implement_stack::top()
{
	return _queue.back();
}
bool two_queues_implement_stack::empty()
{
	return _queue.empty();
}

int main()
{
	two_queues_implement_stack *q = new two_queues_implement_stack;
	q->push(1);
	q->push(2);
	q->push(3);
	q->push(4);
	q->push(5);
	while (!q->empty())
	{
		cout<<" top :"<<q->top()<<endl;
		q->pop();
	}
	delete q;
	q = nullptr;
	return 0;
}
/*
 top :5
 top :4
 top :3
 top :2
 top :1
 */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值