资源描述:
《中缀表达式变后缀表达式算法》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、中缀表达式变后缀表达式算法Intpostfix(qstype*s,char*expression){charx1,x2,x;intj=0;s-->stack[0]=‘#’;s-->top=0;x2=expression[j];If((x1=gettopqstack(s))==NIL)exit(0);while(1){if(x2!=‘+’&&x2!=‘-’&&x2!=‘*’&&x2!=‘/’&&x2!=‘(‘&&x2!=‘)’&&x2!=‘#’){printf(“%c”,x2);x2=expression[++j];
2、}elseif(proceed(x1,x2)==‘<‘){if(!pushqstack(s,x2))exit(0);if((x1=gettopqstack(s))==NIL)exit(0);x2=expression[++j];}elseif(proceed(x1,x2)==‘>‘){if((x=popqstack(s))==NIL)exit(0);printf(“%c”,x);if((x1=gettopqstack(s))==NIL)exit(0);}elseif(proceed(x1,x2)==‘=‘&&x1=
3、‘(‘&&x2=‘)’){if(popqstack(s)==NIL)exit(0);if((x1=gettopqstack(s))==NIL)exit(0);x2=expression[++j];}elseif(proceed(x1,x2)==‘=‘&&x1=‘#‘&&x2=‘#’){return1;}elseif(proceed(x1,x2)==‘‘)break;}Printf(“错误!”);return0;}proceed(x1,x2)完成算符比较功能charproceed(charx1,charx2){c
4、harresult;charmidstring[2];result=‘<‘;Midstring[0]=x2;midstring[1]=‘ ’;if(((x1==‘+’
5、
6、x1==‘-’)&&strstr(“+-)#”,midstring)!=NULL
7、
8、((x1==‘*’
9、
10、x1=‘/’)&&strstr(“+-*/)#”,midstring)!=NULL)
11、
12、(x1==‘)’)&&strstr(“+-*/)#”,midstring)!=NULL)){result=‘>’;}Elseif((x1==‘(‘&&x2
13、==‘)’)
14、
15、(x1==‘#’&&x2=‘#’)){result=‘=‘;}Elseif((x1==‘(‘&&x2==‘#’)
16、
17、(x1==‘)’&&x2=‘(’)
18、
19、(x1==‘#’&&x2==‘)’)){result=‘‘;}Returnresult;}主函数如下:#include#include#include#defineMAXNUM100#defineNIL0typedefcharelemtype;Typedefstruct{elemtypest
20、ack[MAXNUM];inttop;}qstype;voidinitiateqstack(qstype*s);intpushqstack(qstype*s,elemtypex);elemtypepopqstack(qstype*s);elemtypegettopqstack(qstype*s);charproceed(charx1,charx2);Intpostfix(qstype*s,char*expression);main(){charexpression[80]={“A+(B-C/D)*E”};qstyp
21、es;printf(“”);Postfix(&s,strcat(expression,“#”));}