3.5 现有中缀表达式E=((A-B)/C+D*(E-F))*G,写出与E等价的后缀表达式
中缀转后缀表达式网上优质代码太少,本人参考了书本,网络资源,总结出了简洁代码,实属不易,也在此谢谢我那些参考的文章。
#include<iostream>
#include<stack>
using namespace std;
stack<char> s;
void Tran(string n){
for(int i=0;i<n.size();i++){
if(n[i]>='A'&&n[i]<='Z') cout<<n[i];
if(n[i]=='(') s.push(n[i]);//(优先级最高,直接入栈
else if(n[i]==')'){//既然遇到)
while(s.top()!='('){//那么(之前的都弹出
cout<<s.top(); s.pop();
}
s.pop();//将(也弹出
}
else if(n[i]=='+'||n[i]=='-'){//+,-优先级最低
while(!s.empty()&&s.top()!='(') {//只有遇到(,否则全部弹出
cout<<s.top(); s.pop();
}
s.push(n[i]);
}
else if(n[i]=='*'||n[i]=='/'){
while(!s.empty()&&(s.top()=='*'||s.top()=='/')){//(,+,-这三种情况不弹出
cout<<s.top(); s.pop();
}
s.push(n[i]);
}
}
while(!s.empty()){
cout<<s.top(); s.pop();
}
}
int main()
{
string n; cin>>n;
Tran(n);
return 0;
}
//((A-B)/C+D*(E-F))*G
//AB-C/DEF-*+G*