题解 | #逆波兰表达式求值#

逆波兰表达式求值

https://www.nowcoder.com/practice/885c1db3e39040cbae5cdf59fb0e9382

//基础的C语言栈解法,要注意数组角标。本题中使用的结构体其实可以直接用一个数组来代替。QvQ
int evalRPN(char** tokens, int tokensLen ) {
    // write code here
    int result=0;
    struct{
        int integer[10000];
        int topIdx;
    }str={{0},0};

    for(int i=0,j=0;i<tokensLen;i++){
        if(strcmp(tokens[i],"+")==0){
            result=str.integer[str.topIdx-1]+str.integer[str.topIdx-2];
            str.topIdx--;
            str.integer[str.topIdx-1]=result;
        }
        else if(strcmp(tokens[i],"-")==0){
            result=str.integer[str.topIdx-2]-str.integer[str.topIdx-1];
            str.topIdx--;
            str.integer[str.topIdx-1]=result;
        }
        else if(strcmp(tokens[i],"*")==0){
            result=str.integer[str.topIdx-2]*str.integer[str.topIdx-1];
            str.topIdx--;
            str.integer[str.topIdx-1]=result;
        }
        else if(strcmp(tokens[i],"/")==0){
            result=str.integer[str.topIdx-2]/str.integer[str.topIdx-1];
            str.topIdx--;
            str.integer[str.topIdx-1]=result;
        }
        else{
            str.integer[str.topIdx]=atoi(tokens[i]);
            str.topIdx++;
        }
    }
    return str.integer[0];
}
全部评论

相关推荐

09-29 15:34
已编辑
北京航空航天大学 C++
做个有文化的流氓:结果是好的,过程不重要,而且你的offer太多了
软开人,秋招你打算投哪些...
点赞 评论 收藏
分享
评论
4
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务