150. Evaluate Reverse Polish Notation

int stoi(char *s)
{
    int len = strlen(s);
    int sign = 1;
    if(s[0] == '-'){
        sign = -1;
        s += 1;
        len -= 1;
    }
    
    int result = 0;
    for(int i = 0; i < len; i++){
        result = result*10 + s[i] - '0';        
    }
    
    return sign*result;
    
}

int evalRPN(char** tokens, int tokensSize) {
    if(tokensSize == 1)
        return stoi(tokens[0]);
    struct ListNode * dummy = calloc(1, sizeof(struct ListNode));
    bool first  = true;
    double result = 0;
    for(int i = 0; i < tokensSize; i++){
    printf("%s\n", tokens[i]);
    if(!strcmp(tokens[i], "+")||
       !strcmp(tokens[i], "-") ||
       !strcmp(tokens[i], "*") ||
       !strcmp(tokens[i], "/")){
        struct ListNode * p = dummy->next;
        while(p){
            printf("node: %d-> ", p->val);
            p = p->next;
        }
        printf("\n");
        if(first){
            
            if(dummy->next != NULL){
                result = (double)dummy->next->val;
                dummy->next = dummy->next->next;
            }
                     
        }
        int val = 0 ;
        //pop to val
        if(dummy->next != NULL){
            val= dummy->next->val;
            dummy->next = dummy->next->next;
        }
                printf("before result = %lf, val = %d\n", result, val);
        if(first){
        switch(tokens[i][0]){
        case '+': result = val+result;break;
        case '-': result = val-result;break;
        case '*': result = val*result;break;
        case '/': result = val/result;break;
        default:
            break;
        }
            first = false;
        }else{
            
            switch(tokens[i][0]){
        case '+': result = val+result;break;
        case '-': result = result-val;break;
        case '*': result = val*result;break;
        case '/': result = result/val;break;
        default:
            break;
        }       
            
        }
        

        printf("after  result = %lf, val = %d\n", result, val);

    }else{
        //push num
        printf(" else: %s\n", tokens[i]);
        struct ListNode * node = calloc(1, sizeof(struct ListNode));
        node->val = stoi(tokens[i]);
        printf("node->val = %d\n", node->val);
        node->next = dummy->next;
        dummy->next = node;
        
                struct ListNode * p = dummy->next;
        while(p){
            printf("else node: %d-> ", p->val);
            p = p->next;
        }
        printf("\n");
    }


    }
    return result;
}

你可能感兴趣的:(150. Evaluate Reverse Polish Notation)