您好,欢迎访问三七文档
当前位置:首页 > 商业/管理/HR > 销售管理 > 设计将中缀表达式转换为后缀表达式的算法
设计将中缀表达式转换为后缀表达式的算法整代码如下:#includestdio.h#includestdlib.h#includectype.h#includeStack.h#defineMAX30intPrecedence(charch){if(ch=='+'||ch=='-')return2;elseif(ch=='*'||ch=='/')return3;elseif(ch=='('||ch==')')return4;elseif(ch=='@')return1;elsereturn0;}voidChange(char*s1,char*s2){StackS=NewEmpty(MAX);inti=0,j=0,one=0;charch=s1[i];Push('@',S);while(ch!='@'){if(ch=='')ch=s1[++i];elseif(isalnum(ch)!=0){if(one==1){s2[j++]='';}s2[j++]=ch;ch=s1[++i];one=0;}elseif(ch=='('){Push(ch,S);ch=s1[++i];one=1;}elseif(ch==')'){while(Peek(S)!='(')s2[j++]=Pop(S);Pop(S);ch=s1[++i];one=1;}elseif(ch=='+'||ch=='-'||ch=='*'||ch=='/'){while(Peek(S)!='('&&Precedence(Peek(S))=Precedence(ch)){s2[j++]=Pop(S);one=1;}Push(ch,S);ch=s1[++i];one=1;}}while(StackEmpty(S)!=1){s2[j++]=Pop(S);one=1;}s2[j]='\0';}intmain(){chars1[MAX],s2[MAX];printf(Entertheequation:\n);gets(s1);Change(s1,s2);printf(%s\n,s2);return0;}其中:Stack.h如下:#ifndefSTACK_H#defineSTACK_H#includestdio.h#includestdlib.htypedefstructastack*Stack;typedefstructastack{inttop;intmaxtop;char*data;}Astack;StackNewEmpty(intsize){StackS=(Stack)malloc(sizeof(Astack));S-maxtop=size;S-top=-1;S-data=(char*)malloc(size*sizeof(char));returnS;}intStackEmpty(StackS){returnS-top0;}intStackFull(StackS){returnS-top==S-maxtop;}intPeek(StackS){returnS-data[S-top];}voidPush(charx,StackS){if(StackFull(S)){printf(Stackisfull!\n);exit(1);}elseS-data[++S-top]=x;}intPop(StackS){if(StackEmpty(S)){printf(Stackisempty!\n);exit(1);}elsereturnS-data[S-top--];}StackNewStack(intsize){StackS=NewEmpty(size);inti,x,num;printf(Pleaseenterthenumberofdata:\n);scanf(%d,&num);for(i=0;inum;i++){printf(Pleaseenterthe%ddate:\n,i+1);scanf(%c,&x);Push(x,S);}returnS;}voidShowStack(StackS){inti;for(i=0;i=S-top;i++){printf(%c,S-data[i]);}printf(\n);}#endif
本文标题:设计将中缀表达式转换为后缀表达式的算法
链接地址:https://www.777doc.com/doc-5647559 .html