利用C语言和栈实现中缀表达式求值的算法
时间: 2024-06-13 20:05:05 浏览: 196
中缀表达式求值的算法可以通过栈来实现。具体步骤如下:
1. 创建两个栈,一个用于存储操作数,一个用于存储操作符。
2. 从左到右扫描中缀表达式,如果当前字符是数字,则将其压入操作数栈中。
3. 如果当前字符是操作符,则将其与操作符栈的栈顶元素进行比较,如果当前操作符优先级较低,则将操作符栈顶元素弹出并压入操作数栈中,直到当前操作符优先级不低于操作符栈顶元素。
4. 如果当前字符是左括号,则将其压入操作符栈中。
5. 如果当前字符是右括号,则将操作符栈中的元素弹出并压入操作数栈中,直到遇到左括号为止。
6. 当扫描完整个表达式后,将操作符栈中的元素依次弹出并压入操作数栈中,直到操作符栈为空。
7. 最后操作数栈中的元素即为表达式的值。
下面是C语言实现中缀表达式求值的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX_SIZE 100
typedef struct {
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 peek(Stack *s) {
if (is_empty(s)) {
printf("Stack is empty.\n");
exit(1);
}
return s->data[s->top];
}
int is_operator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
int priority(char c) {
if (c == '+' || c == '-') {
return 1;
} else if (c == '*' || c == '/') {
return 2;
} else {
return 0;
}
}
int evaluate(char *expr) {
Stack operand_stack, operator_stack;
init(&operand_stack);
init(&operator_stack);
while (*expr != '\0') {
if (isdigit(*expr)) {
int value = 0;
while (isdigit(*expr)) {
value = value * 10 + (*expr - '0');
expr++;
}
push(&operand_stack, value);
} else if (is_operator(*expr)) {
while (!is_empty(&operator_stack) && priority(peek(&operator_stack)) >= priority(*expr)) {
int b = pop(&operand_stack);
int a = pop(&operand_stack);
char op = pop(&operator_stack);
int result;
switch (op) {
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case '*':
result = a * b;
break;
case '/':
result = a / b;
break;
}
push(&operand_stack, result);
}
push(&operator_stack, *expr);
expr++;
} else if (*expr == '(') {
push(&operator_stack, *expr);
expr++;
} else if (*expr == ')') {
while (peek(&operator_stack) != '(') {
int b = pop(&operand_stack);
int a = pop(&operand_stack);
char op = pop(&operator_stack);
int result; switch (op) {
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case '*':
result = a * b;
break;
case '/':
result = a / b;
break;
}
push(&operand_stack, result);
}
pop(&operator_stack);
expr++;
} else {
expr++;
}
}
while (!is_empty(&operator_stack)) {
int b = pop(&operand_stack);
int a = pop(&operand_stack);
char op = pop(&operator_stack);
int result;
switch (op) {
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case '*':
result = a * b;
break;
case '/':
result = a / b;
break;
}
push(&operand_stack, result);
}
return pop(&operand_stack);
}
int main() {
char expr[MAX_SIZE];
printf("Enter an infix expression: ");
fgets(expr, MAX_SIZE, stdin);
int result = evaluate(expr);
printf("Result: %d\n", result);
return 0;
}
```
阅读全文