c++ 两个栈实现队列

准备两个栈,一个是压入栈,一个是弹出栈。每次操作时,看看弹出栈是否为空,为空时,将压入栈的数据全放入弹出栈。

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

using namespace std;

class two_stacks_implement_queue
{
private:
	stack<int> stack_push;
	stack<int> stack_pop;
	void push_to_pop();
public:
	void push(int data);
	void pop();
	int top();
	bool empty();
};
void two_stacks_implement_queue::push_to_pop()
{
	/*当弹出栈为空时,把压入栈的数据全放入弹出栈*/
	if (stack_pop.empty())
	{
		while (!stack_push.empty())
		{
			stack_pop.push(stack_push.top());
			stack_push.pop();
		}
	}		
}

void two_stacks_implement_queue::push(int data)
{
	stack_push.push(data);
	push_to_pop();
}

void two_stacks_implement_queue::pop()
{
	push_to_pop();
	stack_pop.pop();
}

int two_stacks_implement_queue::top()
{
	push_to_pop();
	return stack_pop.top();
}
bool two_stacks_implement_queue::empty()
{
	return stack_push.empty() && stack_pop.empty();
}

int main()
{
	two_stacks_implement_queue *q = new two_stacks_implement_queue;
	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;
}
/* print
 top :1
 top :2
 top :3
 top :4
 top :5
*/
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值