#逆波兰表达式求值#2023/12/7 今天有点郁闷呢

逆波兰表达式求值

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

#include <string.h>
#include <stdlib.h>

int evalRPN(char** tokens, int tokensLen) {
    int stack[tokensLen];
    int top = -1;

    for (int i = 0; i < tokensLen; i++) {
        if (strcmp(tokens[i], "+") == 0) {
            int a = stack[top--];
            int b = stack[top--];
            stack[++top] = b + a;
        } else if (strcmp(tokens[i], "-") == 0) {
            int a = stack[top--];
            int b = stack[top--];
            stack[++top] = b - a;
        } else if (strcmp(tokens[i], "*") == 0) {
            int a = stack[top--];
            int b = stack[top--];
            stack[++top] = b * a;
        } else if (strcmp(tokens[i], "/") == 0) {
            int a = stack[top--];
            int b = stack[top--];
            stack[++top] = b / a;
        } else {
            stack[++top] = atoi(tokens[i]); // 将字符串转换为整数再入栈
        }
    }

    return stack[top]; // 返回栈顶元素,即表达式的值
}

全部评论

相关推荐

缒梦&独舞:这家公司是这样的,去年给我实习offer了,不过也是面着玩儿的,他周六还要去做公益志愿活动
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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