欢迎来到天天文库
浏览记录
ID:33021693
大小:60.27 KB
页数:8页
时间:2019-02-19
《数据结构之算术表达式求值》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、数据结构Z算术表达式求值c语言编写#include^include#include//defineMAXLEN100typedefstruct{charch;intlevel;}opt;typedefstruct{optst[MAXLEN];inttop;JTstack;〃定义操作栈typedefstruct{doubleD[MAXLEN];inttop;}Nstack;〃定义数据栈voidUnit(Tstack*s){s->top=-l;}//Unitvoi
2、dDUnit(Nstack*s){s->top=-l;〃初始化操作栈〃初始化数据栈}//DUnitcharPush(Tstack*s,optc){s・>top++;s->st[s->top]=c;returnc.ch;〃入操作栈}//PushdoubleDPush(Nstack*s,doublec){s->top++;s->D[s->top]=c;returnc;}//DPush〃入数据栈optTop(Tstack*s){opterror二{$广2};if(s->top>=0)returns->st[s->top];
3、else〃操作栈栈顶returnerror;}//TopdoubleDTop(Nstack*s){讦(s->top>=0)returns->D[s->top];elsereturn0;}//DTop〃数据栈栈顶optPop(Tstack*s)〃岀操作栈{opti;opterror={,$,,-2};if(s->top>=0){i=s->st[s->top];s->st[s->top].ch=' ';s->top-;returni;}elsereturnerror;〃出数据栈〃判断操作栈空intNEmptyfNsta
4、ck*s)〃判断数据栈空}//PopdoubleDPop(Nstack*s){doublei;if(s->top>=0){i=s->D[s->top];s->D[s->top]=' ';s->top~;returni;}elsereturn0;}//DPopintEmpty(Tstack*s)讦(s->top<0)return0;elsereturns->st[s->top].ch;}//Empty讦(s->top<0)return0;elsereturn(int)(s->D[s->top]);}//NEmptyd
5、oublevaluate(char*e)〃计算{TstackT;NstackN;chartmp[MAXLEN]={' '};inti=0,leng;doubled,dp;optA={'+'/l};optR={'-',1};optM={'*2};optD={7',2};optB={'(>1};Unit(&T);DUnit(&N);while(*e!=' '){while(*e>=O&&*e<=11*e==T){while(*e>=O&&*e<='9'11*e=={tmp[i++]=*e++;}d=atof(tmp
6、);DPush(&N,d);leng=strlen(tmp);for(i=0;i=A.level)switch(Pop(&T).ch)dp=DPop(&N)*DPop(&N);DPush(&N,dp);break;case:dp=DPop(&N);dp=DPop(&N)
7、/dp;DPush(&N,dp);break;casedp=DPop(&N)+DPop(&N);DPush(&N,dp);break;case'・':dp=DPop(&N);dp=DPop(&N)-dp;DPush(&N,dp);break;}}Push(&T,A);*e++;}break;caseif(!Empty(&T)11Top(&T).level=R.level){switch(Pop
8、(&T).ch)casedp=DPop(&N)*DPop(&N);DPush(&N,dp);break;case:dp=DPop(&N);dp=DPop(&N)/dp;DPush(&N,dp);break;casedp=DPop(&N)+DPop(&N);DPush(&N,dp);break;casedp=DPop(&N);dp=DPop(&N
此文档下载收益归作者所有