#ifndef EXPRESSION_H
#define EXPRESSION_H
#include <stdio.h>
typedef char SElemType_Sq;
#include "../01 SequenceStack/SequenceStack.c"
typedef SElemType_Sq OperandType;
typedef SElemType_Sq OperatorType;
OperandType EvaluateExpression(char exp[]);
OperatorType GetTop_OPTR(SqStack OPTR);
Status In(SElemType_Sq c);
OperatorType Precede(OperatorType o1, OperatorType o2);
OperandType Operate(OperandType a, OperatorType theta, OperandType b);
#endif
#ifndef EXPRESSION_C
#define EXPRESSION_C
#include "Expression.h"
OperandType EvaluateExpression(char exp[])
{
SqStack OPTR, OPND;
SElemType_Sq e, ch;
OperatorType theta, x;
OperandType a, b;
int i;
InitStack_Sq(&OPTR);
Push_Sq(&OPTR, '#');
InitStack_Sq(&OPND);
i = 0;
ch = exp[i++];
while(ch!='#' || GetTop_OPTR(OPTR)!='#')
{
if(!In(ch))
{
Push_Sq(&OPND, ch);
ch = exp[i++];
}
else
{
switch(Precede(GetTop_OPTR(OPTR), ch))
{
case '<':
Push_Sq(&OPTR, ch);
ch = exp[i++];
break;
case '=':
Pop_Sq(&OPTR, &x);
ch = exp[i++];
break;
case '>':
Pop_Sq(&OPTR, &theta);
Pop_Sq(&OPND, &b);
Pop_Sq(&OPND, &a);
Push_Sq(&OPND, Operate(a, theta, b));
break;
}
}
}
return GetTop_OPTR(OPND);
}
OperatorType GetTop_OPTR(SqStack OPTR)
{
SElemType_Sq e;
GetTop_Sq(OPTR, &e);
return e;
}
Status In(SElemType_Sq c)
{
switch(c)
{
case '+':
case '-':
case '*':
case '/':
case '(':
case ')':
case '#':
return TRUE;
default :
return FALSE;
}
}
OperatorType Precede(OperatorType o1, OperatorType o2)
{
OperatorType f;
switch(o2)
{
case '+':
case '-':
if(o1=='(' || o1=='#')
f = '<';
else
f = '>';
break;
case '*':
case '/':
if(o1=='*' || o1=='/' || o1==')')
f = '>';
else
f = '<';
break;
case '(':
if(o1==')')
{
printf("括号匹配错误!\n");
exit(ERROR);
}
else
f = '<';
break;
case ')':
switch(o1)
{
case '(':
f = '=';
break;
case '#':
printf("输入了错误的括号!\n");
exit(ERROR);
default:
f = '>';
}
break;
case '#':
switch(o1)
{
case '#':
f = '=';
break;
case '(':
printf("表达式中有多余括号!\n");
exit(ERROR);
default:
f = '>';
}
}
return f;
}
OperandType Operate(OperandType a, OperatorType theta, OperandType b)
{
int x, y, z;
x = a - 48;
y = b - 48;
switch(theta)
{
case '+':
return x+y+48;
break;
case '-':
return x-y+48;
break;
case '*':
return x*y+48;
break;
case '/':
return x/y+48;
break;
}
}
#endif
#include "Expression.c"
int main(int argc, char **argv)
{
char opnd;
char *exp = "(2+3)*4*6#";
opnd = EvaluateExpression(exp);
printf("作为示例,%s 的计算结果为:%d\n", exp, opnd-'0');
printf("\n");
return 0;
}