中缀转后缀代码
2024-07-30 16:55:09
发布于:浙江
#include<bits/stdc++.h>
using namespace std;
char s[109];//存储输入的表达式
char ans[109];//存储结果
int level(char s){//规定优先级
if(s=='+' || s=='-') return 1;//加减的优先级更低
else if(s=='' || s=='/') return 2;
}
void infix_to_postfix(char str[]){
stack<char>s;//存储符号
int idx=0;
for(int i=0;str[i]!='\0';i++){//遍历表达式
if(str[i]>='a'&&str[i]<='z'){
ans[idx++]=str[i];
}
else if(str[i]'+' || str[i]'-' || str[i]=='' || str[i]'/'){
if(s.empty() || level(str[i]) > level(s.top())){
s.push(str[i]);
}else{
while(!s.empty() && level(s.top())>=level(str[i])){
if(s.top()'('){
break;
}
ans[idx++]=s.top();
s.pop();
}
s.push(str[i]);
}
}
else{
if(str[i] == '(') s.push(str[i]);
else if(str[i]==')'){
while(s.top()!='('){
ans[idx++]=s.top();
s.pop();
}
s.pop();
}
}
}
while(!s.empty()){
ans[idx++]=s.top();
s.pop();
}
}
int main(){
cin >> s;
infix_to_postfix(s);
cout << ans<<endl;
}
全部评论 2
我的uid是243236811 名字叫上海新客站站长 放我进去呗 球球了 栓q
2024-08-24 来自 江苏
0感觉acgo好冷清
2024-08-03 来自 江苏
0
有帮助,赞一个