用户:
SCS_user_EHQ0z2l6el查看:0 回复:0 评论:0 创建时间:2023-04-02T18:32:06
//中转后缀表达式
#include<iostream>
#include<cstdio>
#include<stack>
using namespace std;
stack <char> s;//栈
char popfront(){
char a=s.top();
s.pop();
return a;
}
int pri(char a){
switch(a){
case '(':
case ')':return 0;
case '+':
case '-':return 1;
case '*':
case '/':return 2;
}
return 0;
}
int main(){
string x;
cin>>x;
for(int i=0;i<x.size();i++){
if('0'<=x[i]&&x[i]<='9'){
int num=0;
while(1){
num*=10;
num+=x[i]-'0';
if((i+1>=x.size())||('0'>x[i+1]||x[i+1]>'9')){
break;
}
i++;
}
cout<<num<<" ";
continue;
}
//后面就是符号处理
if(x[i]=='('||s.empty()||(!s.empty() && pri(s.top())<pri(x[i]))){//喵压入条件:左括号,栈为空,栈顶符号优先级小于当前符号
s.push(x[i]);
}else if(x[i]==')'){
while(s.top()!='(')
cout<<popfront()<<" ";
s.pop();
}else{
while(s.size()&&pri(s.top())>=pri(x[i]))
cout<<popfront()<<" ";
s.push(x[i]);
}
}
while(!s.empty()){
cout<<popfront()<<" ";
}
return 0;
}