看來leetcode上的比較簡單,因為它有限制比較多的input
總之
其實比完是不是加減乘除之後可以直接做運算了
就不用在程式的下段又來一整組的if else.
就降子 XD
int evalRPN(char ** tokens, int tokensSize){
int head = -1;
int *stack = calloc (10000, sizeof(int));
for (int i=0;i<tokensSize; i++)
{
int ops = 0; // +,-,*,/ = 1,2,3,4
if (strcmp(tokens[i],"+")==0)
ops=1;
else if (strcmp(tokens[i],"-")==0)
ops=2;
else if (strcmp(tokens[i],"*")==0)
ops=3;
else if (strcmp(tokens[i],"/")==0)
ops=4;
if (ops==0)
{
stack[++head] = atoi(tokens[i]);
}
else
{
if (head<1)
return -1;
int val1, val2, result;
val1= stack[head-1];
val2= stack[head];
if (ops==1)
result = val1 + val2;
else if (ops==2)
result = val1 - val2;
else if (ops==3)
result = val1 * val2;
else if (ops==4)
result = val1 / val2;
stack[head-1]= result;
head--;
}
}
if (head>0)
return -1;
return stack[head];
}
沒有留言:
張貼留言