/*
编写一个函数,求后缀表达式的值
其中后缀表达式存于一个字符数组exp中,
exp最后一个字符为\0,作为结束符,并且假设后缀表达式中的数字只有一位,
涉及的运算为加减乘除,除法运算为整除运算
*/
#include
#include
typedef struct SqStack {
int data[100];
int top;
}SqStack;
void Push(SqStack* S, int e) {
S->top++;
S->data[S->top] = e;
}
void Pop(SqStack* S, int* e) {
*e = S->data[S->top];
S->top--;
}
int Empty(SqStack* S) {
return S->top == -1;
}
void Init(SqStack* S) {
S->top = -1;
}
int EvaluatePostfixExp(char* exp) {
SqStack S;
Init(&S);
int i = 0;
while (exp[i] != '\0') {
if (exp[i] <= '9'&&exp[i] >= '0') {
Push(&S, exp[i]-'0');
i++;
}
else {
int num1, num2,res;
Pop(&S, &num1);
Pop(&S, &num2);
switch (exp[i]) {
case '+':
res = num1 + num2;
break;
case '-':
res = num1 - num2;
break;
case '*':
res = num1 * num2;
break;
case '/':
res = num1 / num2;
break;
}
Push(&S, res);
i++;
}
}
int res;
Pop(&S, &res);
return res;
}
void main() {
char exp[100] = "123+4*+";//后缀表达式正确值为21
int answer = EvaluatePostfixExp(exp);
printf("%d", answer);//21
getchar();
}
标签:num2,SqStack,int,res,top,C语言,exp,求值,数据结构
来源: https://www.cnblogs.com/wumingoo1/p/11159060.html