算术表达式有前缀表示法、中缀表示法和后缀表示法等形式。日常使用的算术表达式是采用中缀表示法,即二元运算符位于两个运算数中间。请设计程序将中缀表达式转换为后缀表达式。
输入格式: 输入在一行中给出不含空格的中缀表达式,可包含+、-、*、\以及左右括号(),表达式不超过20个字符。
输出格式: 在一行中输出转换后的后缀表达式,要求不同对象(运算数、运算符号)之间以空格分隔,但结尾不得有多余空格。
输入样例:
2+3*(7-4)+8/4
输出样例:
2 3 7 4 - * + 8 4 / +
主要是逆波兰算法,即栈的应用,话不多说,反手就给偶像一个赞,偶像啥都会,,我的偶像是大佬。太强了!!!
#include <iostream>
#include <stack>
using namespace std
;
int main(){
ios
::sync_with_stdio(false);
cin
.tie(0),cout
.tie(0);
string s
;
cin
>> s
;
int len
= 0;
for(int i
= 0;i
<s
.length();i
++){
if(s
[i
]>='0'&&s
[i
]<='9'||s
[i
]=='.')
len
++;
}
if(len
==s
.length()){
cout
<< s
;
return 0;
}
if(s
[0]=='-'){
s
= s
.substr(1);
cout
<< "-";
}
stack
<char> st
;
string res
;
for(int i
= 0;i
<s
.length();i
++){
if(s
[i
]>='0'&&s
[i
]<='9'){
int j
= i
+1;
while((s
[j
] >= '0' && s
[j
] <= '9'||s
[j
]=='.'))
j
++;
res
+= s
.substr(i
,j
-i
);
res
+= " ";
i
= j
-1;
}else{
char op
= s
[i
];
if(op
=='+'&&s
[i
-1]!='('||op
=='-'&&s
[i
-1]!='('){
while(!st
.empty()&&st
.top()!='('){
res
+= st
.top();
res
+= " ";
st
.pop();
}
st
.push(op
);
}else if(op
=='*'||op
=='/'||op
=='('){
st
.push(op
);
}else if(op
==')'){
while(st
.top()!='('){
res
+= st
.top();
res
+= " ";
st
.pop();
}
st
.pop();
}
}
}
while(!st
.empty()){
res
+= st
.top();
if(st
.size()>1)
res
+= " ";
st
.pop();
}
cout
<< res
;
return 0;
}