Evaluate an arithmetic expression given as a string

前端 未结 1 461
不知归路
不知归路 2021-01-29 06:51

I am working on a project where I need to calculate the value of an arithmetic expression given as string.

So that\'s the way I chose to use is such that I run the strin

1条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-29 07:15

    #include 
    #include 
    #include 
    
    typedef struct exp {
        char op;
        char *term;
        struct exp *left;
        struct exp *right;
    } Exp;
    
    Exp *make_exp2(char *str){
        if(!str || !*str) return NULL;//*str == '\0' is format error.
        char *mul = strrchr(str, '*');
        char *div = strrchr(str, '/');
        Exp *node = malloc(sizeof(*node));
        if(mul == NULL && div == NULL){
            node->op = '\0';
            node->term = str;
            node->left = node->right = NULL;
            return node;
        }
        char *op;
        op = mul < div ? div : mul;
        node->op = *op;
        *op = '\0';
        node->left  = make_exp2(str );
        node->right = make_exp2(op+1);
        return node;
    }
    
    Exp *make_exp(char *str){
        if(!str || !*str) return NULL;//*str == '\0' is format error.
        char *minus = strrchr(str, '-');
        char *plus  = strrchr(str, '+');
        if(minus == NULL && plus == NULL)
            return make_exp2(str);
        char *op;
        Exp *node = malloc(sizeof(*node));
        op = minus < plus ? plus : minus;
        node->op = *op;
        *op = '\0';
        node->left  = make_exp(str );
        node->right = make_exp(op+1);
        return node;
    }
    
    #ifdef DEBUG
    
    void print(Exp *exp, int level){
        int i;
        if(exp->op){
            for(i=0;iop);
            for(i=0;iright, level+1);
            printf("\n");
            for(i=0;ileft, level+1);
            printf("\n");
        } else {
            for(i=0;iterm);
        }
    }
    
    #endif
    
    int main(void) {
        char str[] = "3+1-4*6-7";
        Exp *exp = make_exp(str);
    
    #ifdef DEBUG
        print(exp, 0);
    #endif
        //release exp
        return 0;
    }
    

    0 讨论(0)
提交回复
热议问题