bool num(char *token){
//判断字符是否为数字
return strlen(token) > 1 || (token[0] >= '0' && token[0] <= '9');
}
int evalRPN(char ** tokens, int tokensSize){
int n = tokensSize;
int stack[n],top = 0;//初始化一个栈
//遍历整个数组
for(int i = 0;i < n;i++){
char *token = tokens[i];
if(num(token)){
//数字入栈
stack[top++] = atoi(token);//atoi函数将把字符串转换成整型数
}
else{
//数值计算
int num2 = stack[--top];
int num1 = stack[--top];
switch(token[0]){
case '+':
stack[top++] = num1 + num2;
break;
case '-':
stack[top++] = num1 - num2;
break;
case '*':
stack[top++] = num1 * num2;
break;
case '/':
stack[top++] = num1 / num2;
break;
}
}
}
return stack[top-1];
}
LeetCode:150. 逆波兰表达式求值
最新推荐文章于 2024-07-25 17:54:26 发布