#include<iostream>
#include<stack>
#include<unordered_map>
using namespace std;
stack<char> tmp;
unordered_map<char,int> op{
{'+',1},{'-',1},{'*',2},{'/',2}
};
//-2+3*(-7+-4)+8/+4
bool isNum(const string &str,int &i){//运算数前有正负号,小数,整数
if(isdigit(str[i])) return true;
else if(!isdigit(str[i-1]) && str[i-1]!=')' && isdigit(str[i+1]) && (str[i] == '-' || str[i] == '+')){
return true;
}
return false;
}
void transfromNum(string &ans,int &i,const string &str){
if(str[i] == '-') ans += str[i++];
else if(str[i] == '+') i++;
while(i < str.length() && (isdigit(str[i]) || str[i] == '.')){
ans += str[i++];
}
}
int main(){
string str,ans;
cin>>str;
ans = ":";
for(int i = 0; i < str.length(); i++){
if(isNum(str,i)){
transfromNum(ans,i,str);
ans += ' ';
i--;
continue;
}else if(str[i] == '('){
tmp.push(str[i]);
}else if(str[i] == ')'){
while(tmp.size() && tmp.top()!='('){
ans += tmp.top();
ans += ' ';
tmp.pop();
}
tmp.pop();
}else {
while(tmp.size() && op[str[i]] <= op[tmp.top()]){
ans += tmp.top();
ans += ' ';
tmp.pop();
}
tmp.push(str[i]);
}
}
while(tmp.size()){
ans += tmp.top();
ans += ' ';
tmp.pop();
}
for(int i = 1; i < ans.size()-1; i++){
cout<<ans[i];
}
return 0;
}
7-20 表达式转换 (25 分)
最新推荐文章于 2024-03-26 23:34:15 发布