欢迎来到天天文库
浏览记录
ID:15256413
大小:24.00 KB
页数:4页
时间:2018-08-02
《中缀表达式转换为后缀表达式c语言程序》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、//1.h#ifndefSTACK_H#defineSTACK_H#include#includetypedefstructastack*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(S
2、tackS){returnS->top<0;}intStackFull(StackS){returnS->top==S->maxtop;}intPeek(StackS){returnS->data[S->top];}voidPush(charx,StackS){if(StackFull(S)){printf("Stackisfull!");exit(1);}elseS->data[++S->top]=x;}intPop(StackS){if(StackEmpty(S)){printf("Stackisempty!");exit(1);}elsereturnS->data[S->top
3、--];}StackNewStack(intsize){StackS=NewEmpty(size);inti,x,num;printf("Pleaseenterthenumberofdata:");scanf("%d",&num);for(i=0;itop;i++){printf("%c",S->data[i]);}printf("");}
4、#endif//1.c#include#include#include#include"1.h"#defineMAX30intPrecedence(charch){if(ch=='+'
5、
6、ch=='-')return2;elseif(ch=='*'
7、
8、ch=='/')return3;elseif(ch=='('
9、
10、ch==')')return4;elseif(ch=='@')return1;elsereturn0;}voidChange(char*s1,char*s2){StackS=NewEmpty(MAX);inti=0,j=0,o
11、ne=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=='+'
12、
13、ch=='-'
14、
15、ch=='*'
16、
17、ch==
18、'/'){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]=' ';}intmain(){chars1[MAX],s2[MAX];printf("Entertheequation:");gets(s1);Change(s1,s2);printf("%s",s2);return0;}
此文档下载收益归作者所有