题解 | #逆波兰表达式求值#
逆波兰表达式求值
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]; }