用C语言写基于栈的中缀算术表达式求值
时间: 2023-06-09 18:06:25 浏览: 82
好的,您可以这样写一个基于栈的中缀表达式求值程序:
```c
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX_SIZE 50
typedef int ElemType;
typedef struct {
ElemType data[MAX_SIZE];
int top;
} Stack;
void push(Stack *s, ElemType e) {
if (s->top == MAX_SIZE) {
printf("stack overflow\n");
exit(1);
}
s->data[s->top++] = e;
}
ElemType pop(Stack *s) {
if (s->top == 0) {
printf("stack underflow\n");
exit(1);
}
return s->data[--s->top];
}
ElemType peek(Stack *s) {
if (s->top == 0) {
printf("stack empty\n");
exit(1);
}
return s->data[s->top - 1];
}
int is_op(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
int cmp_op(char op1, char op2) {
if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-'))
return 1;
return 0;
}
int eval(char op, int b, int a) {
switch (op) {
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/': return a / b;
}
return 0;
}
int eval_expr(char *expr) {
Stack op_stack, num_stack;
op_stack.top = 0;
num_stack.top = 0;
int i = 0;
while (expr[i] != '\0') {
if (isdigit(expr[i])) {
int num = 0;
while (isdigit(expr[i])) {
num = num * 10 + (expr[i] - '0');
i++;
}
push(&num_stack, num);
} else if (is_op(expr[i])) {
while (op_stack.top > 0 && !cmp_op(expr[i], peek(&op_stack))) {
int b = pop(&num_stack);
int a = pop(&num_stack);
char op = pop(&op_stack);
int result = eval(op, b, a);
push(&num_stack, result);
}
push(&op_stack, expr[i]);
i++;
} else if (expr[i] == '(') {
push(&op_stack, '(');
i++;
} else if (expr[i] == ')') {
while (peek(&op_stack) != '(') {
int b = pop(&num_stack);
int a = pop(&num_stack);
char op = pop(&op_stack);
int result = eval(op, b, a);
push(&num_stack, result);
}
pop(&op_stack);
i++;
} else {
i++;
}
}
while (op_stack.top > 0) {
int b = pop(&num_stack);
int a = pop(&num_stack);
char op = pop(&op_stack);
int result = eval(op, b, a);
push(&num_stack, result);
}
return pop(&num_stack);
}
int main(void) {
char expr[MAX_SIZE];
printf("Enter an infix expression: ");
scanf("%s", expr);
int result = eval_expr(expr);
printf("Result: %d\n", result);
return 0;
}
```
该程序使用两个栈来实现中缀表达式求值,一个保存操作数,一个保存操作符。遍历表达式的每个字符,如果是数字,则从当前位置开始解析数字,并将其压入操作数栈中;如果是操作符,则依次将栈顶符号与当前符号比较优先级,如果栈顶符号优先级较高,则弹出两个操作数和一个操作符,计算出结果并将其压入操作数栈中,否则将当前符号压入操作符栈中;如果是左括号,则直接将其压入操作符栈中;如果是右括号,则依次弹出操作数栈和操作符栈中的元素,直到遇到左括号为止,并将计算结果压入操作数栈中;其他字符则忽略。最后,当操作符栈不为空时,依次弹出操作数栈和操作符栈中的元素,计算出最终结果。