表达式求值
结果有 空指针
乘法和减法有误
#include "stdio.h"
#include "stdlib.h"
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
#define OVERFLOW 0
#define ERROR 0
#define OK 1
typedef char SElemType;
typedef struct
{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
int InitStack(SqStack *S)
{
S->base=(SElemType *)malloc(STACK_INIT_SIZE * sizeof(SElemType));
if(!S->base)exit(OVERFLOW);
S->top=S->base;
S->stacksize=STACK_INIT_SIZE;
return OK;
}
int GetTop(SqStack *S)
{
SElemType *e=0;
if(S->top==S->base) return ERROR;
*e=*(S->top-1);
return *e;
}
int Push(SqStack *S,SElemType e)
{
if(S->top-S->base>=S->stacksize)
{
S->base=(SElemType *)realloc(S->base,
(S->stacksize+STACKINCREMENT) * sizeof(SElemType));
if(!S->base)exit(OVERFLOW);
S->top=S->base+S->stacksize;
S->stacksize+=STACKINCREMENT;
}
*S->top++=e;
return OK;
}
void Pop(SqStack *S,SElemType *e)
{
if(S->top==S->base) exit(ERROR);
*e=*--S->top;
}
char OP[]={'+','-','*','/','(',')','#'};
int precede[7][7]={
1,1,2,2,2,1,1,
1,1,2,2,2,1,1,
1,1,1,1,2,1,1,
1,1,1,1,2,1,1,
2,2,2,2,2,3,0,
1,1,1,1,0,1,1,
2,2,2,2,2,0,3};
int In(char c,char op[]) /*查看输入的是否为运算符*/
{
int i=0;
while(i<=7)
if(c==op[i++])
return 1;
return 0;
}
char Precede(char op,char c) /*比较两个运算符的的优先级*/
{
int i;
int op_x;
int op_y;
for(i=0;i<7;i++)
{
if(op==OP[i]) op_x=i;
if(c==OP[i]) op_y=i;
}
switch(precede[op_x][op_y])
{
case 1: return '>';
case 2: return '<';
case 3: return '=';
}
}
/* int Operate(char a,char x,char b)
{
switch(x)
{
case '+':return a+b;
case '-':return a-b;
case '*':return a*b;
case '/':return a/b;
}
} */
char Operate(int a,char x,int b)
{
switch(x)
{
case '+':return a+b-'0';
case '-':return a-b+'0';
case '*':return (a-'0')*(b-'0')+'0';
case '/':return (a-'0')/(b-'0')+'0';
}
}
char EvaluateExpression()
{
char a,b,c,e,x;
SqStack *OPTR,*OPND;
OPTR=(SqStack *)malloc(sizeof(SqStack));
OPND=(SqStack *)malloc(sizeof(SqStack));
InitStack(OPTR); Push(OPTR,'#');
InitStack(OPND);
c=getchar();
while(c!='#'|| GetTop(OPTR)!='#')
{
if(!In(c,OP))
{
Push(OPND,c);
c=getchar();
}
else
switch(Precede(GetTop(OPTR),c)) /*对输入的c与原来的OPTR->TOP进行优先级的比较*/
{
case'<': /*栈顶元素优先权低*/
Push(OPTR,c); c=getchar();
break;
case'=': /*脱掉括号并接收下一个字符,“=”只有‘(’=‘)’和‘#’=‘#’的情况*/
Pop(OPTR,&e); c=getchar();
break;
case'>': /*退栈并用OPTR栈的栈顶运算符对OPND的最后两个数进行运算,且把结果放入OPND*/
Pop(OPTR,&x);
Pop(OPND,&a); Pop(OPND,&b);
Push(OPND,Operate(a,x,b));
break;
}
}
return(GetTop(OPND));
}
main()
{
printf("\n%c",EvaluateExpression());
}