#逆波兰表达式求值#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]; // 返回栈顶元素,即表达式的值
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
04-08 05:32
点赞 评论 收藏
分享
头顶尖尖的程序员:我是26届的不太懂,25届不应该是找的正式工作吗?为什么还在找实习?大四还实习的话是为了能转正的的岗位吗
点赞 评论 收藏
分享
存一千万就可以进大厂实习
石圪节公社发型师:有存一千万的实力还实习个嘚,直接躺平
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务