用C写后缀表达式求值代码
时间: 2023-09-01 21:10:36 浏览: 77
我可以为您提供C语言中后缀表达式求值的代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define STACK_INIT_SIZE 20
#define STACKINCREMENT 10
typedef char ElemType;
typedef struct {
ElemType *base;
ElemType *top;
int stacksize;
} SqStack;
void InitStack(SqStack *S) {
S->base = (ElemType *) malloc(STACK_INIT_SIZE * sizeof(ElemType));
if (!S->base)
exit(1);
S->top = S->base;
S->stacksize = STACK_INIT_SIZE;
}
void Push(SqStack *S, ElemType e) {
if (S->top - S->base >= S->stacksize) {
S->base = (ElemType *) realloc(S->base,
(S->stacksize + STACKINCREMENT) * sizeof(ElemType));
if (!S->base)
exit(1);
S->top = S->base + S->stacksize;
S->stacksize += STACKINCREMENT;
}
*(S->top)++ = e;
}
void Pop(SqStack *S, ElemType *e) {
if (S->top == S->base)
return;
*e = *--S->top;
}
ElemType GetTop(SqStack *S) {
if (S->top != S->base)
return *(S->top - 1);
else
exit(1);
}
int StackEmpty(SqStack *S) {
if (S->top == S->base)
return 1;
else
return 0;
}
int EvaluateExpression(char Expression[]) {
SqStack S;
InitStack(&S);
char c, d;
int i, num, a, b;
i = num = 0;
c = Expression[i];
while (c != '\0') {
if (isdigit(c)) {
num = 0;
while (isdigit(c)) {
num = num * 10 + c - '0';
i++;
c = Expression[i];
}
Push(&S, num);
} else {
Pop(&S, &a);
Pop(&S, &b);
switch (c) {
case '+':
num = b + a;
break;
case '-':
num = b - a;
break;
case '*':
num = b * a;
break;
case '/':
num = b / a;
break;
default:
exit(1);
}
Push(&S, num);
i++;
c = Expression[i];
}
}
Pop(&S, &num);
return num;
}
int main() {
char expression[100] = "234*+";
printf("后缀表达式:%s\n", expression);
printf("结果为:%d\n", EvaluateExpression(expression));
return 0;
}
```
您可以将需要计算的后缀表达式放在 `EvaluateExpresssion` 函数中 `char expression[]` 数组中的引号内。例如,想要计算 "23 4 * 5 +" 的值,可以将 `char expression[100]` 改为 `char expression[100] = "23 4 * 5 +"`,最终结果将会输出至屏幕上。
阅读全文