6-5 Evaluate Postfix Expression (25分)
解题思路:计算后缀表达式的值
1、遇到数字入栈
2、遇到符号则出栈计算
3、或栈中仅剩1个数,则栈中值即为所求,否则,错误
ElementType EvalPostfix( char *expr ) { ElementType stack[Max_Expr]; char b[Max_Expr]; int i=0,j=0; int top=-1; ElementType x,y; while(expr[i]!='\0') { while(expr[i]==' ') i++; if(isdigit(expr[i])||expr[i]=='.') { b[j++]=expr[i]; if(expr[i+1]==' '||expr[i+1]=='\0') { b[j]='\0'; stack[++top]=atof(b); j=0; } } else { if(expr[i]=='-'||expr[i]=='+') { if(isdigit(expr[i+1])) { b[j++]=expr[i]; } else if(expr[i+1]==' '||expr[i+1]=='\0') { if(top) { x=stack[top--]; y=stack[top]; if(expr[i]=='+') stack[top]=y+x; else stack[top]=y-x; } else return Infinity; } } else if(expr[i]=='*'||expr[i]=='/') { if(top) { x=stack[top--]; y=stack[top]; if(expr[i]=='*') stack[top]=y*x; else { if(x) stack[top]=y/x; else return Infinity; } } else return Infinity; } } i++; } if(!top) return stack[top]; else return Infinity; }
勤能补拙,熟能生巧