您的位置:首页 > 其它

利用表达式树,计算一个加减乘除(可带括号)的表达式

2017-07-29 11:03 483 查看
#include <iostream>

#include <iterator>

#include <vector>

#include <cstdio>

#include <map>

#include <cstring>
using namespace std;

const int maxn = 255;

struct node

{

    node* left;

    node* right;

    char op[100];

    node():left(NULL),right(NULL){}

};
node* dfs(char* s,int x,int y)

{

    int c1 = -1,c2 = -1,d = 0;

    if(y-x==1)

    {

        node* p = new node;

        (p->op)[0] = s[x];

        return p;

    }

    int flag = 0;

    for(int i = x;i<y;i++)

    {

        switch(s[i])

        {

        case '(':

            d++;

            flag = 1;

            break;

        case ')':

            d--;

            flag = 1;

            break;

        case '+':

        case '-':

            if(!d)

                c1 = i;

            break;

        case '*':

        case '/':

            if(!d)

                c2 = i;

            break;

        }

    }

    if(c1<0)

        c1 = c2;

    if(c1<0)

    {

        if(flag)

            return dfs(s,x+1,y-1);

        else

        {

            node* p1 = new node;

            for(int j = x;j<y;j++)

            {

                (p1->op)[j-x] = s[j];

            }

            return p1;

        }

    }

    node* p  = new node;

    (p->op)[0] = s[c1];

    p->left = dfs(s,x,c1);

    p->right = dfs(s,c1+1,y);

    return p;

}
int cal(node* p)

{

    char c = (p->op)[0];

    if(c>47&&c<58)

    {

        int num = 0;

        if(strlen(p->op)==1)

            num = 0+c-'0';

        else

        {

            for(int i = 0;i<strlen(p->op);i++)

            {

                num *= 10;

                num += 0+(p->op)[i]-'0';

            }

        }

        return num;

    }

    if(c=='+')

        return cal(p->left)+cal(p->right);

    if(c=='-')

        return cal(p->left)-cal(p->right);

    if(c=='*')

        return cal(p->left)*cal(p->right);

    if(c=='/')

        return cal(p->left)/cal(p->right);

}
int main()

{

    char str[maxn];

    while(~scanf("%s",str))

    {

        int len = strlen(str);

        node* root = dfs(str,0,len);

        int sum = cal(root);

        cout<<sum<<endl;

    }

    return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐