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

逆波兰表达式求值

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

看到这个题解没有c语言题解,只能自己摸索。首先很明显这道题用栈来实现,根据题目意思只需要创建数字栈即可,后面只要遇到运算符就用栈内的两个数字进行相应的运算。再把结果压入栈内,这里为了方便起见就用int数组模仿栈。
代码比较暴力易懂
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param tokens string字符串一维数组 
 * @param tokensLen int tokens数组长度
 * @return int整型
 *
 * C语言声明定义全局变量请加上static,防止重复定义
 */
int evalRPN(char** tokens, int tokensLen ) {
    // write code here
    char theta[tokensLen];
    int num[tokensLen];
    int top1=0,top2=0;
    int result;
    //printf("%c",tokens[3][1]);
    for(int i=0;i<tokensLen;i++)
    {    //先判断是否为运算符
        if(*tokens[i]!='+'&&*tokens[i]!='*'&&*tokens[i]!='/')
        {
            if(*tokens[i]=='-'&&tokens[i][1]=='\0')
            {
                result=num[top1-2]-num[top1-1];
                top1-=2;
                num[top1++]=result;
            }
            else
            {
                int m=0;
                int number=0;
                if(tokens[i][0]=='-')
                    m=1;
                while(tokens[i][m]!='\0')
                {
                    number=number*10+(tokens[i][m]-'0');
                    m++;
                }
                if(tokens[i][0]=='-')
                    num[top1++]=number*(-1);
                else
                    num[top1++]=number;
            }
        }
        else
        {
            if(*tokens[i]=='+')
            {
                result=num[top1-2]+num[top1-1];
                top1-=2;
                num[top1++]=result;
            }
            /*else if(*tokens[i]=='-')
            {
                result=num[top1-2]-num[top1-1];
                top1-=2;
                num[top1++]=result;
            }*/
            else if(*tokens[i]=='*')
            {
                result=num[top1-2]*num[top1-1];
                top1-=2;
                num[top1++]=result;
            }
            else if(*tokens[i]=='/')
            {
                result=num[top1-2]/num[top1-1];
                top1-=2;
                num[top1++]=result;
            }
        }
    }
    return num[top1-1];
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
08-07 15:21
不是哥们,我就随便投投,你咋这么热情
25届上岸PDD_微...:同学,试试我们部门
点赞 评论 收藏
分享
点赞 评论 收藏
分享
点赞 评论 收藏
分享
Lorn的意义:1.你这根本就不会写简历呀,了解太少了 2.你这些项目经历感觉真的没啥亮点啊,描述的不行,重写书写一下让人看到核心,就继续海投 注意七八月份ofer还是比较多的,越往后机会越少,抓住时机,抓紧检查疏漏,加油查看图片
点赞 评论 收藏
分享
评论
2
1
分享

创作者周榜

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