参考课本《数据结构》(C语言版第二版)P77
#include <stdio.h>
#include <stdlib.h>
struct Stack {
int Top;
int MaxSize;
char *ch;
};
struct Stack *CreateStack(int MaxSize);//建立空顺序栈
void Push(struct Stack *&S, char ch);//元素入栈
char GetTop(struct Stack *S);//提取栈顶元素
char Operate(char a, char ch, char b);//a与b的运算
char Precede(char oper1, char oper2);//比较运算符的优先级
int IsChar(char ch);//判断ch是运算符还是数字
char EvaluateExpression();//完成表达式的求值
int main() {
struct Stack *S;
S = CreateStack(100);
printf("%d", EvaluateExpression() - '0' );
return 0;
}
struct Stack *CreateStack(int MaxSize) {
struct Stack *S;
S = (struct Stack *)malloc(sizeof(struct Stack));
S->ch = (char *)malloc(sizeof(struct Stack) * MaxSize);
S->MaxSize = MaxSize;
S->Top = -1;
return S;
}
void Push(struct Stack *&S, char c) {
if (S->Top == S->MaxSize - 1)
return;
S->ch[++S->Top] = c;
}
char GetTop(struct Stack *S) {
return S->ch[S->Top] ;
}
char Operate(char a, char ch, char b) {
if (ch == '+')
return (a - '0' ) + (b - '0') + '0';
else if (ch == '-')
return (a - '0' ) - (b - '0') + '0';
else if (ch == '*')
return (a - '0' ) * (b - '0') + '0';
else if (ch == '/')
return (a - '0' ) / (b - '0') + '0';
}
char Precede(char oper1, char oper2) {
if (oper1 == '+' || oper1 == '-') {
if (oper2 == '+' || oper2 == '-' || oper2 == ')' || oper2 == '#')
return '>';
else
return '<';
} else if (oper1 == '*' || oper1 == '/') {
if (oper2 == '(')
return '<';
else
return '>';
} else if (oper1 == '(') {
if (oper2 == ')')
return '=';
else if (oper2 == '#')
return false;
else
return '<';
} else if (oper1 == ')') {
if (oper2 != '(')
return '>';
else
return false;
} else if (oper1 == '#') {
if (oper2 == '#')
return '=';
else if (oper2 == ')')
return false;
else
return '<';
}
}
int IsChar(char ch) {
switch (ch) {
case '+':
case '-':
case '*':
case '/':
case '(':
case ')':
case '#':
return true;
break;
default :
return false;
}
}
char EvaluateExpression() {
struct Stack *OPND;//存放数字
struct Stack *OPTR;//存放符号
OPND = CreateStack(100);
OPTR = CreateStack(100);
Push(OPTR, '#');
char ch;
scanf("%c", &ch);
while (ch != '#' || GetTop(OPTR) != '#') {
if (!IsChar(ch)) {
Push(OPND, ch);
scanf("%c", &ch);
} else
switch (Precede(GetTop(OPTR), ch)) {
case '<':
Push(OPTR, ch);
scanf("%c", &ch);
break;
case '>': {
char theta = GetTop(OPTR);
OPTR->Top--;
char b = GetTop(OPND);
OPND->Top--;
char a = GetTop(OPND);
OPND->Top--;
Push(OPND, Operate(a, theta, b));
break;
}
case '=':
OPTR->Top--;
scanf("%c", &ch);
break;
}
}
return GetTop(OPND);
}