即将通关x03,x03需要的拿去用
2024-07-30 16:54:10
发布于:浙江
//中缀转后缀
#include<bits/stdc++.h>
using namespace std;
char s[109],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])){//先判空再用s.top()不然会报错
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);
return 0;
}
这里空空如也
有帮助,赞一个