C++两个栈实现队列(含main函数)

版权声明:不推荐直接照抄代码,至少要在理解后的前提下;欢迎评论 https://blog.csdn.net/weixin_40457801/article/details/89680497

使用两个栈实现一个队列

最近一直再重温c++,就把最近遇到的题目和自己写的代码都记录下来吧,自己也可以复习

问题:使用两个栈实现一个队列
很经典的c++与数据结构问题,首先有思路一定要求得对栈和队列足够熟悉,我这里对于基础知识就不多展开了,上网搜或看《数据结构c语言版》。

代码:

#include<iostream>
#include<stack> //STL容器栈
//#include<queue> //队列
using namespace std;

//两个栈实现队列
//第一个栈相当于进行倒置,然后从上往下压入栈2,从栈2再弹出
class solution
{
public:
	stack<int> s1;
	stack<int> s2;
	void push(int node){
		s1.push(node);
	}
	int pop(){
		//当s2不为空时,将s1压入到s2
       if(s2.empty())
	   {   
		   while(!s1.empty())
				{int a=s1.top();
				 s2.push(a);
				 s1.pop();}
	   }
	   //弹出s2,此时即为队列的弹出
	   int b=s2.top();
	   s2.pop();
	   return b;

	}
};


int main()
{
solution ss;
ss.push(7);
ss.push(77);
ss.push(777);

cout<<ss.pop()<<endl;
cout<<ss.pop()<<endl;

}

结果

逐一压入7,77,777,按照First in First out得,结果正确
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_40457801/article/details/89680497
今日推荐