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

#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;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值