后缀表达式求值C语言
时间: 2023-12-03 19:39:41 浏览: 136
以下是C语言实现后缀表达式求值的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX_STACK_SIZE 100
typedef struct {
int top;
int data[MAX_STACK_SIZE];
} Stack;
void init(Stack *s) {
s->top = -1;
}
int is_empty(Stack *s) {
return s->top == -1;
}
int is_full(Stack *s) {
return s->top == MAX_STACK_SIZE - 1;
}
void push(Stack *s, int value) {
if (is_full(s)) {
printf("Stack overflow\n");
exit(1);
}
s->data[++s->top] = value;
}
int pop(Stack *s) {
if (is_empty(s)) {
printf("Stack underflow\n");
exit(1);
}
return s->data[s->top--];
}
int evaluate_postfix(char *expr) {
Stack s;
init(&s);
for (int i = 0; expr[i] != '\0'; i++) {
if (isdigit(expr[i])) {
push(&s, expr[i] - '0');
} else {
int op1 = pop(&s);
int op2 = pop(&s);
switch (expr[i]) {
case '+':
push(&s, op2 + op1);
break;
case '-':
push(&s, op2 - op1);
break;
case '*':
push(&s, op2 * op1);
break;
case '/':
push(&s, op2 / op1);
break;
default:
printf("Invalid operator\n");
exit(1);
}
}
}
return pop(&s);
}
int main() {
char expr[] = "23+45+*";
int result = evaluate_postfix(expr);
printf("Result: %d\n", result);
return 0;
}
```
阅读全文