设计并实现将一个中缀表达式转换成逆波兰式-然后对此逆波兰表达式求值的算法。

整理文档很辛苦,赏杯茶钱您下走!

免费阅读已结束,点击下载阅读编辑剩下 ...

阅读已结束,您可以下载文档离线阅读编辑

资源描述

/*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());}

1 / 8
下载文档,编辑使用

©2015-2020 m.777doc.com 三七文档.

备案号:鲁ICP备2024069028号-1 客服联系 QQ:2149211541

×
保存成功