前缀表达式求值

题目

前缀表达式是一种把运算符前置的算术表达式,例如普通的表达式 2+32+3 的波兰表示法为 + 2 3+ 2 3 。波兰表达式的优点是运算符之间不必有优先级关系,也不必用括号改变运算次序,例如 (2+3)∗4(2+3)∗4 的波兰表示法为 ∗ + 2 3 4∗ + 2 3 4。

本题求解波兰表达式的值,其中运算符包括 + - * /四个。

解法1:栈

​//前缀表达式可以看作反写后缀表达式,用栈实现反转即可
//后缀表达式链接:https://blog.csdn.net/2301_77744823/article/details/141255774?spm=1001.2014.3001.5502
#include <bits/stdc++.h>
using namespace std;
stack<double>num;
stack<string>st;
int main(){
    string s;
    int x;
    while(cin>>s)st.push(s);
    while(st.size()){
        s=st.top();
        st.pop();
        if(s[0]>='0'&&s[0]<='9'){
            stringstream sin;
            sin<<s;
            sin>>x;
            num.push(double(x));
        }
        else{
            double a,b;
            b=num.top();
            num.pop();
            a=num.top();
            num.pop();
            if(s[0]=='+')num.push(a+b);
            if(s[0]=='-')num.push(a-b);
            if(s[0]=='*')num.push(a*b);
            if(s[0]=='/')num.push(a/b);
        }
    }
    cout<<fixed<<setprecision(3)<<num.top();
    return 0;
}

​

   解法2:递归(表达式树)

        上图展示的为前缀表达式 + 13 * 5 9 的表达式树


#include <bits/stdc++.h>
using namespace std;
double cal(){
    string s;
    cin>>s;
    //符号,递归下降
    if(s=="+")return cal()+cal();
    if(s=="-")return cal()-cal();
    if(s=="*")return cal()*cal();
    if(s=="/")return cal()/cal();
    return stof(s);//数字,转成浮点数
}
int main(){
    cout<<fixed<<setprecision(3)<<cal();
    return 0;
}

      

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值