算术表达式有前缀表示法、中缀表示法和后缀表示法等形式。前缀表达式指二元运算符位于两个运算数之前,例如2+3*(7-4)+8/4的前缀表达式是:+ + 2 * 3 - 7 4 / 8 4。请设计程序计算前缀表达式的结果值。
输入格式:
输入在一行内给出不超过30个字符的前缀表达式,只包含+、-、*、/以及运算数,不同对象(运算数、运算符号)之间以空格分隔。
输出格式:
输出前缀表达式的运算结果,保留小数点后1位,或错误信息ERROR。
输入样例:
+ + 2 * 3 - 7 4 / 8 4
输出样例:
13.0
思路
参考:【表达式转换 (25 分)】
上面这篇文章写的很清楚,思路很清晰
当栈为空或者栈顶运算符的优先级小于当前二元运算符的优先级时,将该二元运算符导入。
倘若栈顶运算符的优先级大于或等于当前二元运算符的优先级,又分为以下两种情况,1.若栈顶运算符为( 符号,则直接将该运算符插入即可; 2.若栈顶运算符不是( 符号,则优先输出栈内的元素,直到碰到( 符号或者栈为空,然后将当前二元运算符插入。
实现
#include<iostream>
#include<cstring>
#include<vector>
#include<algorithm>
#include<stack>
#include<map>
#include<list>
#include<cmath>
using namespace std;
typedef long long ll;
#define N 205
int main(){
string s;
cin >> s;
stack<char> st;
map<char,int> mp;
mp['+']=1;mp['-']=1;
mp['*']=2;mp['/']=2;
mp['(']=3;mp[')']=3;
int len = s.length(),first = 1;
for(int i=0;i<len;i++){
if((i==0||i&s[i-1]=='(')&&(s[i]=='+'||s[i]=='-')){
if(!first) cout << " ";
// 正负号处理
if(s[i]=='-') cout << "-";
while(i+1<len&&s[i+1]>='0'&&s[i+1]<='9'||s[i+1]=='.'){
i++;
cout << s[i];
}
first = 0;
}
else if(s[i]>='0'&&s[i]<='9'){
if(!first) cout << " ";
printf("%c",s[i]);
while(i+1<len&&s[i+1]>='0'&&s[i+1]<='9'||s[i+1]=='.'){
i++;
cout << s[i];
}
first = 0;
}
else if(s[i]==')') {
while(!st.empty()&&st.top()!='('){
printf(" %c",st.top());
st.pop();
}
if(st.top()=='(') st.pop();
}
else if(st.empty()||mp[s[i]]>mp[st.top()]){
st.push(s[i]);
}
else {
while(!st.empty()&&st.top()!='('){
printf(" %c",st.top());
st.pop();
}
st.push(s[i]);
}
}
while(!st.empty()){
printf(" %c",st.top());
st.pop();
}
return 0;
}