c语言计算后缀表达式
时间: 2023-12-20 15:06:32 浏览: 139
以下是C语言计算后缀表达式的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 100
typedef struct Stack {
int top;
int data[MAX_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_SIZE - 1;
}
void push(Stack *s, int x) {
if (is_full(s)) {
printf("Stack is full.\n");
exit(1);
}
s->data[++s->top] = x;
}
int pop(Stack *s) {
if (is_empty(s)) {
printf("Stack is empty.\n");
exit(1);
}
return s->data[s->top--];
}
int calculate(int a, int b, char op) {
switch (op) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
return a / b;
default:
printf("Invalid operator.\n");
exit(1);
}
}
int evaluate(char *expr) {
Stack s;
init(&s);
char *token = strtok(expr, " ");
while (token != NULL) {
if (isdigit(token[0])) {
push(&s, atoi(token));
} else {
int b = pop(&s);
int a = pop(&s);
push(&s, calculate(a, b, token[0]));
}
token = strtok(NULL, " ");
}
return pop(&s);
}
int main() {
char expr[MAX_SIZE];
printf("Enter postfix expression: ");
fgets(expr, MAX_SIZE, stdin);
expr[strlen(expr) - 1] = '\0';
int result = evaluate(expr);
printf("Result: %d\n", result);
return 0;
}
```
阅读全文