资源描述:
《数据结构运算符的优先级》由会员上传分享,免费在线阅读,更多相关内容在应用文档-天天文库。
1、#include#include#include#defineSTACK_INIT_SIZE100#defineSTACKCREMENT10#defineOPSIZE7#defineERROR0#defineOK1#defineOVERFLOW-1unsignedcharPrior[7][7]={//算符间的优先关系'>','>','<','<','<','>','>','>','>','<','<','<','>','>','>','>','>','>','<','>','>','>','>','>','>','<',
2、'>','>','<','<','<','<','<','=','','>','>','>','>','','>','>','<','<','<','<','<','','='};charOP[OPSIZE]={'+','-','*','/','(',')','#'};typedefstruct{float*base;float*top;intstacksize;}SqStack;//建立空栈intInitStack(SqStack&S){S.base=(float*)malloc(STACK_INIT_SIZE*sizeof(float));if(!S.base)exit(O
3、VERFLOW);S.top=S.base;S.stacksize=STACK_INIT_SIZE;returnOK;}//取栈顶元素charGetTop(SqStack&S){if(S.base==S.base)returnERROR;return*(S.top-1);}//入栈intPush(SqStack&S,chare){if(S.top-S.base>=S.stacksize){S.base=(float*)realloc(S.base,(S.stacksize+STACKCREMENT)*sizeof(float));if(!S.base)exit(OVERFLOW
4、);S.top=S.base+S.stacksize;S.stacksize+=STACKCREMENT;}*S.top++=e;returnOK;}//出栈intPop(SqStack&S,float&e){if(S.base==S.base)returnERROR;e=*--S.top;returnOK;}//运算操作floatOperate(floata,chartheta,floatb){switch(theta){case'+':returna+b;case'-':returnb-a;case'*':returna*b;case'/':returnb/a;defaul
5、t:return0;}}//判断是否为运算符intIn(charc,char*OP){boolFind=false;for(inti=0;i6、turnOpOrd(c,OP)];}//算术表达式求值的算符优先算法。//设OPTR和OPND分别为运算符栈和运算数栈,OP为运算符集合。charEvaluateExpression(){charTempData[20];floatData,a,b;chartheta,c,x,Dr[2];SqStackOPND;//运算数栈SqStackOPTR;//运算符栈InitStack(OPTR);Push(OPTR,'#');InitStack(OPND);c=getchar();while(c!='#'
7、
8、GetTop(OPTR)!='#'){if(!In(c,OP)){//不是运
9、算符则进栈Push(OPND,c);c=getchar();}elseswitch(Precede(GetTop(OPTR),c)){case'<':Push(OPTR,c);c=getchar();break;case'=':Pop(OPTR,x);c=getchar();break;case'>':Pop(OPTR,theta);Pop(OPND,b);Pop(OPND,a);Push(OPND,Operate(a,theta,b));break;}}returnGetTop(OPND)