HDU-1237 中缀表达式转后缀表达式 后缀表达式求值

中缀表达式转后缀表达式 :
扫描中缀表达式:
1.数字,直接输出
2.左括号,左括号入栈
3.右括号,不断取栈顶并输出,直到栈顶为左括号,最后左括号出栈
4.运算符,不断取栈顶并输出,直栈顶优先级高于此运算符,最后新运算符入栈

后缀表达式求值:
扫描后缀表达式:
1.数字,入栈
2.运算符,取出栈顶两个数,运算,结果入栈
3.最后栈里剩下的一个数即为答案

#include<iostream>
#include<iomanip>
#include<unordered_map>
#include<stack>
#include<string>
using namespace std;
inline double cal(double a,double b,char op){
	switch(op){
		case '+':return a+b;
		case '-':return a-b;
		case '*':return a*b;
		case '/':return a/b;
	}
	return 0;
}
string::iterator i;
inline double dio(){
	double x=0;
	while(isdigit(*i))x=x*10+*i-'0',++i;
	return x;
}
unordered_map<char,int>op;
stack<char>sta;
stack<double>st;
string s;
int main(){
	ios::sync_with_stdio(false);
	cin.tie(nullptr),cout.tie(nullptr);
	op['(']=op[')']=0;
	op['+']=op['-']=1;
	op['*']=op['/']=2;
	while(getline(cin,s)){
		if(s=="0")break;
		string suffix;
		i=s.begin();
                while(i!=s.end()){
			if(op.count(*i)){
				if(*i==')'){
					while(sta.top()!='(')suffix+=sta.top(),sta.pop();
					sta.pop();
				}else if(sta.empty()||*i=='('||op[sta.top()]<op[*i])sta.push(*i);
				else if(op[sta.top()]>=op[*i]){
					while(!sta.empty()&&op[sta.top()]>=op[*i])suffix+=sta.top(),sta.pop();
					sta.push(*i);
				}
			}else suffix+=*i;
			++i;
			if(i==s.end()){
				suffix+=' ';
				while(!sta.empty())suffix+=sta.top(),sta.pop();
			}
                }
                cout<<suffix<<'\n';
                i=suffix.begin();
                double a,b;
		while(i!=suffix.end()){
			if(op.count(*i)){
				a=st.top(),st.pop();
				b=st.top(),st.pop();
				st.push(cal(b,a,*i));
			}else if(*i!=' ')st.push(dio());
			++i;
                }
                cout<<setiosflags(ios::fixed)<<setprecision(2)<<st.top()<<'\n';
                st.pop();
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值