中缀表达式转为后缀表达式-C++实现

这个思路知识点相信大家都可以搜到,我直接放出C++实现的代码,用电栈和队列,为了区别放入队列的是符号还是数字,我们用一个结构体去标识即可

#include<iostream>
#include<map> 
#include<stack>
#include<queue> 
using namespace std;
//设置优先级 
map<char ,int> p;
/*
测试用例:
1 + 2
3


4 + 2 * 5 - 7 / 11
13.36
 
*/

//初始化
struct node{
	double num;	//操作数 
	char op;		//操作符 
	bool flag;		//标志:true为操作数,false为操作符 
}; 

//中缀转为后缀并求值 ,没有括号 
int main(){
	//设置字符优先级
	p['+']=p['-'] = 1;
	p['*']=p['/'] = 2;
	string str;
	getline(cin,str);
	int len=str.length();
	stack<node> s;	//符号栈 
	queue<node> q;	//后缀队列 
	int i=0;
	int num=0;
	while(i<len){
		if(str[i]>='0'&&str[i]<='9'){
			while(str[i]>='0'&&str[i]<='9'&&i<len){
				num=num*10+str[i]-'0';
				i++;
			}
			node N;
			N.num=num;
			N.flag=true;
			q.push(N);
			num=0;
		}
		else if(str[i]==' '){
			i++;
		}
		else if(str[i]=='+' || str[i]=='-'){
			while(!s.empty() && p[s.top().op]>=1 ){
				node N=s.top();
				s.pop();
				q.push(N);
			}
			node N;
			N.op=str[i];
			N.flag=false;
			s.push(N);
			i++;
		}
		else if(str[i]=='*' || str[i]=='/'){
			while(!s.empty() && p[s.top().op]>=2 ){
				node N=s.top();
				s.pop();
				q.push(N);
			}
			node N;
			N.op=str[i];
			N.flag=false;
			s.push(N);
			i++;
		}
	}
	//将栈中剩余的符号出栈 
	while(!s.empty()){
		node N=s.top();
		q.push(N);
		s.pop();
	}
	//打印后缀表达式 
	/*
	while(!q.empty()){
		node N=q.front();
		q.pop();
		if(N.flag){
			cout<<N.num;
		}else{
			cout<<N.op;
		}
	}
	cout<<endl;
	*/
	
	
	stack<int> ans;
	//进行后缀表达式求值
	while(!q.empty()){
		node N=q.front();
		q.pop();
		if(N.flag){
			//数字
			ans.push(N.num); 
		}else{
			int t2=ans.top();
			ans.pop();
			int t1=ans.top();
			ans.pop();
			if(N.op=='+'){
				ans.push(t1+t2);
			}else if(N.op=='-'){
				ans.push(t1-t2);
			}else if(N.op=='*'){
				ans.push(t1*t2);
			}else if(N.op=='/'){
				ans.push(t1/t2);
			}
		}
	} 
	if(!ans.empty())
		cout<<ans.top()<<endl;
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小吴同学GOGOGO

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值