C语言 栈 求表达式.docxVIP

  • 1
  • 0
  • 约2.81千字
  • 约 4页
  • 2023-03-12 发布于湖北
  • 举报
#includestdio.h #includemalloc.h #includemath.h #includeprocess.h #define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define STACK_INIT_SIZE 100 #define STACKINCERMENT 10 typedef int Status; typedef int OperandType; typedef char OperatorType; typedef struct SqStack{ int *base; int *top; int stacksize; }SqStack; char a[8][8]={ {\0,+,-,*,/,(,),=}, {+,,,,,,,}, {-,,,,,,,}, {*,,,,,,,}, {/,,,,,,,}, {(,,,,,,=,\0}, {),,,,,\0,,}, {=,,,,,,\0,=}}; Status In(char c) //判断c 是否运算符函数 { if(c48||c57) return TRUE; else return FALSE; }//In Status InitStack(SqStack s) //初始化栈函数 { s.base=(int *)malloc(STACK_INIT_SIZE*sizeof(int)); if(!s.base) exit(OVERFLOW); s.top=s.base; s.stacksize=STACK_INIT_SIZE; return OK; }//InitStack int GetTop(SqStack s) //取栈顶元素函数 { int e; if(s.top==s.base) return ERROR; e=*(s.top-1); return e; }//GetTop Status Push(SqStack s,int e) // 压栈函数 { if(s.top-s.base=s.stacksize){ s.base=(int *)realloc(s.base,(s.stacksize+STACKINCERMENT)*sizeof(int)); if(!s.base) exit(OVERFLOW); s.top=s.base+s.stacksize; s.stacksize+=STACKINCERMENT; } *s.top++=e; return OK; }//Push Status Pop(SqStack s,int e) //出栈函数 { if(s.top==s.base) return ERROR; e=*--s.top; return OK; }//Pop OperatorType Precede(OperatorType c1,OperatorType c2) //判断两个运算符优先级函数 { int i,j; for(i=0;i8a[i][0]!=c1;i++); //从第 0 列查找操作符c1 if(i=8){ printf(Operator error!1\n); exit(OVERFLOW); } for(j=0;j8a[0][j]!=c2;j++); //从第 0 行查找操作符c2 if(j=8){ printf(Operator error!2\n); exit(OVERFLOW); } return a[i][j]; }//Precede Status StackEmpty(SqStack s) //判断栈是否为空函数 { if(s.base==s.top) return TRUE; else return FALSE; }//StackEmpty OperandType Operate(OperandType a,OperatorType thera,OperandType b) //求两个元素通过指定运算的结果函数 { switch(thera){ case+: return a+b; case-: return a-b; case*: return a*b; case/: if(b==0) { printf(Divide zero!\n); //除数为 0,程序结束exit(OVERFLOW); } else return a/b; default: printf(Operator error!\n); //操作符错误,程序结束exit(OVERFLOW); } }//Operate OperandType EvaluateExpression() //求表达式值函数 { int i,t,a,b,thera,f=0,j; char c=0

文档评论(0)

1亿VIP精品文档

相关文档