编程语言
首页 > 编程语言> > 逆波兰表达式改写(C++)

逆波兰表达式改写(C++)

作者:互联网

#include<iostream>
#include<cstring>

using namespace std;

class EV{
    public:
        EV(const int &vR, const int& vN)
        {
            result = vR;
            n =vN;
        }
        EV(){}
        int getResult() const
        {
            return result;
        }
        int getN() const
        {
            return n;
        }
        void setResult(const int& r)
        {
            result = r;
        }
        void setN(const int& N)
        {
            n = N;
        }
    private:
        int result, n ;

};

EV evaluate(const char* x)
{
    EV ev(0,0);
    EV v1, v2;
    if(*x == 0) return ev;
    if(x[0] >= '0' && x[0] <= '9')
    {
        ev.setResult(x[0] - '0') ;
        ev.setN(1);
        return ev;
    }
    v1 = evaluate(x + 1);
    v2 = evaluate(x + 1 + v1.getN());
    if(x[0] == '+') ev.setResult(v1.getResult() + v2.getResult());
    if(x[0] == '*') ev.setResult(v1.getResult() * v2.getResult());
    if(x[0] == '-') ev.setResult(v1.getResult() - v2.getResult());
    ev.setN(  1 + v1.getN() + v2.getN());
    return ev;
}

int main(int argc, char* argv[])
{
    string s = "-+3*5+261";
    const EV &ev = evaluate((char*)(s.c_str()));
    int res = ev.getResult();
    cout << res << endl;
    return 0;
}

 

标签:const,int,C++,改写,result,vN,return,EV,表达式
来源: https://www.cnblogs.com/fourmi/p/12531686.html