1.源码实现
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int evalRPN(char **tokens, int tokensLen)
{
int *number = (int *)malloc(sizeof(int) * tokensLen);
int res = atoi(tokens[0]);
int u;
int i = 0, j = 0;
while(i < tokensLen)
{
if(strcmp(tokens[i], "+") != 0 && strcmp(tokens[i], "-") != 0 && strcmp(tokens[i], "*") != 0 && strcmp(tokens[i], "/") != 0)
{
number[j] = atoi(tokens[i]);
j++;
}
else
{
if(tokens[i][0] == '+')
{
u = number[j-1];
number[j-2] += u;
j--;
}
else if(tokens[i][0] == '-')
{
u = number[j-1];
number[j-2] -= u;
j--;
}
else if(tokens[i][0] == '*')
{
u = number[j-1];
number[j-2] *= u;
j--;
}
else if(tokens[i][0] == '/')
{
u = number[j-1];
number[j-2] /= u;
j--;
}
}
i++;
}
res = number[0];
free(number);
number = NULL;
return res;
}
int main()
{
char a[10][20] = {"2", "0", "+"};
char *tokens[10];
int i;
int res;
for(i=0; i<10; i++)
{
tokens[i] = a[i];
}
res = evalRPN(tokens, 3);
printf("%d\n", res);
return 0;
}
2.编译源码
$ gcc -o test test.c -std=c89
3.运行及其结果
$ ./test
2
网友评论