当前位置: 首页> 教育> 大学 > 简洁明了!中缀表达式转为后缀表达式规则及代码

简洁明了!中缀表达式转为后缀表达式规则及代码

时间:2025/7/11 15:13:49来源:https://blog.csdn.net/yykYYK2010/article/details/142308536 浏览次数:0次

 简单来说,就是弄两个栈,判断执行:

上代码: 

#include<iostream>
#include<stack>
#include<cstring>
using namespace std;
stack<char>s1,s2;
char now;
int main(){string c;cin>>c;for(int i=0;i<c.length();i++){if(c[i]>='0'&&c[i]<='9'){s2.push(c[i]);if(!(c[i+1]>='0'&&c[i+1]<='9'))s2.push('.');	} else if(c[i]=='+'||c[i]=='-'){while(!s1.empty()&&s1.top()!='('){s2.push(s1.top());s1.pop();}s1.push(c[i]);}else if(c[i]=='*'||c[i]=='/'){while(!s1.empty()&&(s1.top()=='*'||s1.top()=='/')){s2.push(s1.top());s1.pop();}s1.push(c[i]);}else if(c[i]=='('){s1.push(c[i]);}else if(c[i]==')'){while(s1.top()!='('){s2.push(s1.top());s1.pop();}s1.pop();}}while(!s1.empty()){s2.push(s1.top());s1.pop();}while(!s2.empty()){s1.push(s2.top());s2.pop();}while(!s1.empty()){cout<<s1.top();s1.pop();}return 0;
}

因为csp中常考的就是中、后缀的计算,所以先写这些,后续再更

关键字:简洁明了!中缀表达式转为后缀表达式规则及代码

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: