题解 | #逆波兰表达式求值#
逆波兰表达式求值
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();
}
腾讯成长空间 5879人发布