解题思路
遍历tokens,遇到数字入栈,遇到运算符号,从栈中取出两个数组经过运算以后,将结果入栈
代码(Java)
class Solution {
public int evalRPN(String[] tokens) {
//栈
Deque<Integer> stack= new LinkedList<>();
//遍历tokens
for(int i=0; i<tokens.length; i++){
//遇到加减乘除符号
if(tokens[i].equals("+")){
//从栈顶取出两个数
int a = stack.removeFirst();
int b = stack.removeFirst();
//进行运算以后又从栈顶压入
stack.addFirst(b+a);
}else if(tokens[i].equals("-")){
//从栈顶取出两个数
int a = stack.removeFirst();
int b = stack.removeFirst();
//进行运算以后又从栈顶压入
stack.addFirst(b-a);
}else if(tokens[i].equals("*")){
//从栈顶取出两个数
int a = stack.removeFirst();
int b = stack.removeFirst();
//进行运算以后又从栈顶压入
stack.addFirst(b*a);
}else if(tokens[i].equals("/")){
//从栈顶取出两个数
int a = stack.removeFirst();
int b = stack.removeFirst();
//进行运算以后又从栈顶压入
stack.addFirst(b/a);
}else{
//否则转成数字压入栈中
stack.addFirst(Integer.valueOf(tokens[i]));
}
}
return stack.removeFirst();
}
}
代码(C)
//strcmp(str1,str2),若str1=str2,则返回零;
int get_result(char *a,int b,int c)
{
if(!strcmp(a,"+"))return b+c;
if(!strcmp(a,"-"))return b-c;
if(!strcmp(a,"*"))return b*c;
if(!strcmp(a,"/"))return b/c;
return 0;
}
int evalRPN(char ** tokens, int tokensSize){
int i=0,j=0;
//指针data
int *data=(int*)malloc((tokensSize/2+2)*sizeof(int));
while(j<tokensSize)
{
if(strcmp(tokens[j],"+")&&strcmp(tokens[j],"-")&&strcmp(tokens[j],"*")&&strcmp(tokens[j],"/"))
//数据
{
// int atoi(const char *str) 把参数 str 所指向的字符串转换为一个整数(类型为 int 型)。
data[i++]=atoi(tokens[j]);
}
//运算符
else{
//出栈 运算 入栈
data[i-2]=get_result(tokens[j],data[i-2],data[i-1]);
i=i-1;
}
j++;
}
return data[i-1];
}