资源描述:
《设计并实现将一个中缀表达式转换成逆波兰式-然后对此逆波兰表达式求值的算法。.docx》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、/*Note:YourchoiceisCIDE*/#include"stdio.h"#include"stdlib.h"#include"string.h"#defineSTACK_INIT_SIZE100//初始大小#defineSTACK_INCR_SIZE10//增加大小#defineOVERFLOW-2typedefcharSELemType;typedefstruct{SELemTypebase[STACK_INIT_SIZE];inttop;}SqStack;voidInitStack(SqStack*s)//
2、初始化{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
3、)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]!=' '){m=m*10+(a[i]-'0');i++;}while(b[j]!=' '){n=n*10+(b[j]-'0');j++;}O='+';switch(O){case'+':result=m+n;break
4、;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(result>0);for(j=i-1;j>=0;j--){result=R%10;R=R/10;str[j]=(result+'0');}str[i]=' ';returnstr;}SELemTypePrecede(SELemTypea,SELemTypeb){intm,n;SEL
5、emTypeoperat[7][7]={'>','>','<','<','<','>','>','>','>','<','<','<','>','>','>','>','>','>','<','>','>','>','>','>','>','<','>','>','<','<','<','<','<','=','','>','>','>','>','','>','>','<','<','<','<','<','','=',};switch(a){case'+':m=0;break;case'-':m=1;break;cas
6、e'*':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];}charEvaluateExpress
7、ion(){SqStackOPND,OPTR;charc,x,theta;chara,b;inti=0,j;InitStack(&OPTR);Push(&OPTR,'#');InitStack(&OPND);c=getchar();while(c!='#'
8、
9、GetTop(OPTR)!='#'){if(c!='+'&&c!='-'&&c!='*'&&c!='/'&&c!='('&&c!=')'&&c!='#'){Push(&OPND,c);str[i]=c;i++;c=getchar();}elseswitch(Prece
10、de(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