llllmz

导航

150. 逆波兰表达式求值c

int f(int a ,int b,char c){
    if(c=='+') return a+b;
    if(c=='-') return a-b;
    if(c=='/') return a/b;
    return a*b;
}

int evalRPN(char** tokens, int tokensSize) {
    int* stack=(int*)malloc(sizeof(int)*tokensSize);
    int top=0;
    int index=0;
    while(index<tokensSize){
        if( tokens[index][0] >='0' && tokens[index][0]<='9' || (tokens[index][0] =='-' &&  tokens[index][1]!=0)  ){
            stack[top++]=atoi(tokens[index++]);
        }else{
            int b=stack[--top];
            int a=stack[--top];
            int c=f(a,b,tokens[index][0]);
            printf("%d %d %c %d",a,b,tokens[index][0],c);
            stack[top++]=c;
            index++;
        }
    }
    return stack[0];
}

 

posted on 2024-03-19 16:42  神奇的萝卜丝  阅读(5)  评论(0)    收藏  举报