《堆栈四则运算.doc》由会员分享,可在线阅读,更多相关《堆栈四则运算.doc(6页珍藏版)》请在金锄头文库上搜索。
1、#include #include #include #include #define TRUE 1#define FALSE 0#define STACK_INIT_SIZE 100#define STACKINCREMENT 20/*/typedef structint *pbase;int *ptop;int stacksize;stack;/*/char operator7=+-*/()!;char optr;int opnd=-1;int result;char prioritytable77=,o,pbase)free(s-pbase);s-ptop=s-pbase=NULL;/*
2、/栈不空,则返回栈顶int gettop(stack s)return *(s.ptop-1);/*/压栈int pushstack(stack *s,int e)if (s-ptop-s-pbase=STACK_INIT_SIZE)s-pbase=(int*)realloc(s-pbase,(s-stacksize+STACKINCREMENT)*sizeof(int);if (!s-pbase)return 0;s-ptop=s-pbase+s-stacksize;s-stacksize=s-stacksize+STACKINCREMENT;*(s-ptop+)=e;return 1;/*
3、/int pop(stack *s,int*e)if (s-ptop=s-pbase)return 0;*e=*-(s-ptop);return 1;/*/比较两个字符的优先级char checkchar(char operator_1,char operator_2)int i,j;i=strchr(operator,operator_1)-operator;j=strchr(operator,operator_2)-operator;return prioritytableij;/*/判断是否为操作数isoperator(char ch)if (strchr(operator,ch)ret
4、urn TRUE;else return FALSE;/*/从键盘获得输入void getinput()char buffer20;char ch;int data;data=0;ch=getch();while (ch!=13&!isoperator(ch)if (ch=0&ch0)bufferdata=0;opnd=atoi(buffer);else opnd=-1;/*/计算表达式int calc(int a,int b,char ch)switch(ch)case +:return a+b;case -:return a-b;case *:return a*b;default:if (
5、b=0)printf(除数不能为0);return 0;else return b/a;evaluateexpression()int temp;char ch;int ich;int a,b;char topoptr;int topopnd;stack OPTR=initstack();stack OPND=initstack();if (!pushstack(&OPTR,!)return FALSE;getinput();while(optr!=!|gettop(OPTR)!=!)if (opnd=0)pushstack(&OPND,opnd);switch(checkchar(getto
6、p(OPTR),optr)case :pop(&OPTR,&ich);pop(&OPND,&a);pop(&OPND,&b);ch=(char)(ich);pushstack(&OPND,calc(a,b,ch);opnd=-1;break;if (OPND.ptop=OPND.pbase&opnd0)printf(nn谢谢使用!n);exit(1);else if (OPND.ptop=OPND.pbase)result=opnd;elseresult=gettop(OPND);destorystack(&OPND);destorystack(&OPTR);return TRUE;void
7、message()printf(|-|n);printf(| 堆栈的四则运算 |n);printf(|-|n);printf(|从键盘上直接输入表达式,以回车键结束。如:5*(6+1)回车键|n);printf(|注1:不输入任何数按回车退出程序。 |n);printf(|注2:程序不接受除四则运算以外的任何键盘输入。 |n);printf(|注3:程序只接受正确的表达式。 |n);printf(|-|n);main()int i;message();for (i=1;i+)printf(表达式%i:,i);if (evaluateexpression()printf(=%dn,result);else printf(计算遇到错误n);