int stoi(char *s)
{
int len = strlen(s);
int sign = 1;
if(s[0] == '-'){
sign = -1;
s += 1;
len -= 1;
}
int result = 0;
for(int i = 0; i < len; i++){
result = result*10 + s[i] - '0';
}
return sign*result;
}
int evalRPN(char** tokens, int tokensSize) {
if(tokensSize == 1)
return stoi(tokens[0]);
struct ListNode * dummy = calloc(1, sizeof(struct ListNode));
bool first = true;
double result = 0;
for(int i = 0; i < tokensSize; i++){
printf("%s\n", tokens[i]);
if(!strcmp(tokens[i], "+")||
!strcmp(tokens[i], "-") ||
!strcmp(tokens[i], "*") ||
!strcmp(tokens[i], "/")){
struct ListNode * p = dummy->next;
while(p){
printf("node: %d-> ", p->val);
p = p->next;
}
printf("\n");
if(first){
if(dummy->next != NULL){
result = (double)dummy->next->val;
dummy->next = dummy->next->next;
}
}
int val = 0 ;
//pop to val
if(dummy->next != NULL){
val= dummy->next->val;
dummy->next = dummy->next->next;
}
printf("before result = %lf, val = %d\n", result, val);
if(first){
switch(tokens[i][0]){
case '+': result = val+result;break;
case '-': result = val-result;break;
case '*': result = val*result;break;
case '/': result = val/result;break;
default:
break;
}
first = false;
}else{
switch(tokens[i][0]){
case '+': result = val+result;break;
case '-': result = result-val;break;
case '*': result = val*result;break;
case '/': result = result/val;break;
default:
break;
}
}
printf("after result = %lf, val = %d\n", result, val);
}else{
//push num
printf(" else: %s\n", tokens[i]);
struct ListNode * node = calloc(1, sizeof(struct ListNode));
node->val = stoi(tokens[i]);
printf("node->val = %d\n", node->val);
node->next = dummy->next;
dummy->next = node;
struct ListNode * p = dummy->next;
while(p){
printf("else node: %d-> ", p->val);
p = p->next;
}
printf("\n");
}
}
return result;
}
150. Evaluate Reverse Polish Notation
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 原题 对于一个逆波兰数学表达式求值 ["2", "1", "+", "3", "*"] -> ((2 + 1) *...
- Evaluate the value of an arithmetic expression in Reverse...