请你用c语言写一个中缀表达式求值问题的算法
时间: 2024-05-09 19:21:21 浏览: 84
关于中缀表达式求值c语言
以下是中缀表达式求值问题的算法(使用栈):
```
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX_SIZE 100
typedef struct {
int data[MAX_SIZE];
int top;
} 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)) {
fprintf(stderr, "stack is full\n");
exit(EXIT_FAILURE);
}
s->data[++s->top] = x;
}
int pop(Stack *s) {
if (is_empty(s)) {
fprintf(stderr, "stack is empty\n");
exit(EXIT_FAILURE);
}
return s->data[s->top--];
}
int top(Stack *s) {
if (is_empty(s)) {
fprintf(stderr, "stack is empty\n");
exit(EXIT_FAILURE);
}
return s->data[s->top];
}
int precedence(char op) {
switch (op) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
default:
fprintf(stderr, "invalid operator: %c\n", op);
exit(EXIT_FAILURE);
}
}
int evaluate(char *expr) {
Stack op_stack, val_stack;
char *p = expr;
init(&op_stack);
init(&val_stack);
while (*p) {
if (isspace(*p)) {
p++;
continue;
}
if (isdigit(*p)) {
int val = 0;
while (isdigit(*p)) {
val = val * 10 + (*p - '0');
p++;
}
push(&val_stack, val);
} else if (*p == '+' || *p == '-' || *p == '*' || *p == '/') {
while (!is_empty(&op_stack) && precedence(top(&op_stack)) >= precedence(*p)) {
int val2 = pop(&val_stack);
int val1 = pop(&val_stack);
char op = pop(&op_stack);
int result;
switch (op) {
case '+':
result = val1 + val2;
break;
case '-':
result = val1 - val2;
break;
case '*':
result = val1 * val2;
break;
case '/':
result = val1 / val2;
break;
default:
fprintf(stderr, "invalid operator: %c\n", op);
exit(EXIT_FAILURE);
}
push(&val_stack, result);
}
push(&op_stack, *p);
p++;
} else {
fprintf(stderr, "invalid character: %c\n", *p);
exit(EXIT_FAILURE);
}
}
while (!is_empty(&op_stack)) {
int val2 = pop(&val_stack);
int val1 = pop(&val_stack);
char op = pop(&op_stack);
int result;
switch (op) {
case '+':
result = val1 + val2;
break;
case '-':
result = val1 - val2;
break;
case '*':
result = val1 * val2;
break;
case '/':
result = val1 / val2;
break;
default:
fprintf(stderr, "invalid operator: %c\n", op);
exit(EXIT_FAILURE);
}
push(&val_stack, result);
}
return pop(&val_stack);
}
int main() {
char expr[MAX_SIZE];
printf("Enter an infix expression: ");
fgets(expr, MAX_SIZE, stdin);
printf("Result: %d\n", evaluate(expr));
return 0;
}
```
这个算法的思路是使用两个栈,一个存储操作符,一个存储操作数。遍历中缀表达式的每个字符,如果是数字,则将其转换成整数并压入操作数栈;如果是操作符,则将其与操作符栈的栈顶元素比较优先级,如果优先级低于等于栈顶元素,则将栈顶元素弹出,同时从操作数栈弹出两个操作数进行计算,并将计算结果压入操作数栈;如果优先级高于栈顶元素,则将操作符压入操作符栈。最后,将剩余的操作符依次弹出进行计算,直到操作符栈为空,此时操作数栈中只剩下一个元素,即为中缀表达式的值。
阅读全文