llllmz

导航

150. 逆波兰表达式求值 C

int evalRPN(char** tokens, int tokensSize) {
    int* stack=(int*)malloc(sizeof(int)*tokensSize);
    for(int i=0;i<tokensSize;i++) stack[i]=0;
    int top=-1;
    for(int i=0;i<tokensSize;i++){
        if(tokens[i][0]=='+'){
            int tempa=stack[top--];
            int tempb=stack[top--];
            stack[++top]=tempa+tempb;
        }else if(tokens[i][0]=='/'){
            int tempa=stack[top--];
            int tempb=stack[top--];
            stack[++top]=tempb/tempa;
        }else if(tokens[i][0]=='-'&&tokens[i][1]==0){
            int tempa=stack[top--];
            int tempb=stack[top--];
            stack[++top]=tempb-tempa;
        }else if(tokens[i][0]=='*'){
            int tempa=stack[top--];
            int tempb=stack[top--];
            stack[++top]=tempb*tempa;
        }else{
            stack[++top]=atoi(tokens[i]);
        }
    }
    return stack[0];
}

结果:

posted on 2024-02-29 20:07  神奇的萝卜丝  阅读(12)  评论(0)    收藏  举报