您好,欢迎访问三七文档
当前位置:首页 > 商业/管理/HR > 销售管理 > 设计并实现将一个中缀表达式转换成逆波兰式-然后对此逆波兰表达式求值的算法。
/*Note:YourchoiceisCIDE*/#includestdio.h#includestdlib.h#includestring.h#defineSTACK_INIT_SIZE100//初始大小#defineSTACK_INCR_SIZE10//增加大小#defineOVERFLOW-2typedefcharSELemType;typedefstruct{SELemTypebase[STACK_INIT_SIZE];inttop;}SqStack;voidInitStack(SqStack*s)//初始化{s-top=-1;}voidPush(SqStack*s,SELemTypee)//进栈{if(s-top==STACK_INIT_SIZE-1)exit(OVERFLOW);elses-base[++s-top]=e;}voidPop(SqStack*S,SELemType*e)//删除栈顶元素{if(S-top==-1)exit(OVERFLOW);else*e=S-base[S-top--];}charGetTop(SqStackS)//取栈顶元素{SELemTypee;if(S.top==-1)exit(OVERFLOW);elsee=S.base[S.top];returne;}SELemTypeOperate(SELemTypea[],SELemTypeO,SELemTypeb[]){charstr[10];intm=0,n=0,result,i=0,j=0,O,R;while(a[i]!='\0'){m=m*10+(a[i]-'0');i++;}while(b[j]!='\0'){n=n*10+(b[j]-'0');j++;}O='+';switch(O){case'+':result=m+n;break;case'-':result=m-n;break;case'*':result=m*n;break;case'/':result=m/n;break;}R=result;i=0;do{result=result/10;i++;}while(result0);for(j=i-1;j=0;j--){result=R%10;R=R/10;str[j]=(result+'0');}str[i]='\0';returnstr;}SELemTypePrecede(SELemTypea,SELemTypeb){intm,n;SELemTypeoperat[7][7]={'','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','=','','','','','','','','','','','','','','','=',};switch(a){case'+':m=0;break;case'-':m=1;break;case'*':m=2;break;case'/':m=3;break;case'(':m=4;break;case')':m=5;break;case'#':m=6;break;}switch(b){case'+':n=0;break;case'-':n=1;break;case'*':n=2;break;case'/':n=3;break;case'(':n=4;break;case')':n=5;break;case'#':n=6;break;}returnoperat[m][n];}charEvaluateExpression(){SqStackOPND,OPTR;charc,x,theta;chara,b;inti=0,j;InitStack(&OPTR);Push(&OPTR,'#');InitStack(&OPND);c=getchar();while(c!='#'||GetTop(OPTR)!='#'){if(c!='+'&&c!='-'&&c!='*'&&c!='/'&&c!='('&&c!=')'&&c!='#'){Push(&OPND,c);str[i]=c;i++;c=getchar();}elseswitch(Precede(GetTop(OPTR),c)){case'':Push(&OPTR,c);c=getchar();break;case'=':Pop(&OPTR,&x);c=getchar();break;case'':Pop(&OPTR,&theta);str[i]=theta;i++;Pop(&OPND,&b);Pop(&OPND,&a);Push(&OPND,Operate(a,theta,b));break;}}c=GetTop(OPND);/*DestroyStack(OPTR);DestroyStack(OPND);*/returnc;}voidmain(){printf(%c,EvaluateExpression());}
本文标题:设计并实现将一个中缀表达式转换成逆波兰式-然后对此逆波兰表达式求值的算法。
链接地址:https://www.777doc.com/doc-5647248 .html