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

逆波兰表达式求值

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

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 *
 * @param tokens string字符串一维数组
 * @param tokensLen int tokens数组长度
 * @return int整型
 */
//需要指针top
//定义出栈,入栈,输出栈顶元素的函数,遇到数字出栈,和运算符计算后入栈

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int top = -1;
int stack[10000];

//进栈
void push(int num) {
    top++;
    stack[top] = num;
}
//出栈
int pop() {
    if (top == -1) {
        return -1;
    }
   
    return stack[top--];
}

int evalRPN(char** tokens, int tokensLen ) {
    // write code here
    int a, b; //进栈的元素
    //strcmp处理当入栈元素为负数时,返回整个负数
    for (int i = 0; i < tokensLen; i++) {
            if (strcmp(tokens[i], "+") == 0) {
                a = pop();
                b = pop();
                push(a + b);
            } else if (strcmp(tokens[i], "-") == 0) {
                a = pop();
                b = pop();
                push(b - a);
            } else if (strcmp(tokens[i], "*") == 0) {
                a = pop();
                b = pop();
                push(b * a);
            }
                else if (strcmp(tokens[i], "/") == 0) {
                    a = pop();
                    b = pop();
                    push(b / a);
                } else
                    push(atoi(tokens[i]));//把字符串转换成整型数

            }
        
        return pop();
    }

全部评论

相关推荐

ResourceUtilization:四六级不愧是大学最有用的证之一
点赞 评论 收藏
分享
03-31 17:40
已编辑
门头沟学院 算法工程师
程序员牛肉:小牛肉来也! 也不要焦虑啦,你第一志愿还没有结束,只是回到人才库(泡大池子等待各个部门挑选)而已。仅仅代表你不符合这个组的用人标准,并不能够说明你在本次暑期实习中没机会加入美团了。 还是平复好心态,不断的复盘,等待下一次面试就好了。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务