用栈写表达式求值c语言
时间: 2023-05-20 11:05:37 浏览: 141
可以使用栈来实现表达式求值,具体步骤如下:
1. 定义两个栈,一个用来存储操作数,一个用来存储操作符。
2. 从左到右扫描表达式,遇到操作数则压入操作数栈中。
3. 遇到操作符时,将其与操作符栈顶元素比较,如果优先级高于栈顶元素,则将其压入操作符栈中;否则,将操作符栈顶元素弹出并与操作数栈顶的两个元素进行运算,将结果压入操作数栈中,直到操作符栈顶元素优先级低于当前操作符。
4. 扫描完表达式后,将操作符栈中的所有操作符依次弹出并与操作数栈顶的两个元素进行运算,将结果压入操作数栈中,直到操作符栈为空。
5. 最终操作数栈中的唯一元素即为表达式的值。
以下是用栈写表达式求值的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 push(Stack *s, int x) {
if (s->top == MAX_SIZE - 1) {
printf("Stack overflow!\n");
exit(1);
}
s->data[++s->top] = x;
}
int pop(Stack *s) {
if (s->top == -1) {
printf("Stack underflow!\n");
exit(1);
}
return s->data[s->top--];
}
int peek(Stack *s) {
if (s->top == -1) {
printf("Stack underflow!\n");
exit(1);
}
return s->data[s->top];
}
int is_empty(Stack *s) {
return s->top == -1;
}
int is_operator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
int precedence(char c) {
if (c == '+' || c == '-') {
return 1;
} else if (c == '*' || c == '/') {
return 2;
} else {
return 0;
}
}
int evaluate_expression(char *expr) {
Stack operand_stack, operator_stack;
operand_stack.top = -1;
operator_stack.top = -1;
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(&operand_stack, num);
} else if (is_operator(expr[i])) {
while (!is_empty(&operator_stack) && precedence(peek(&operator_stack)) >= precedence(expr[i])) {
int op2 = pop(&operand_stack);
int op1 = pop(&operand_stack);
char op = pop(&operator_stack);
int result;
switch (op) {
case '+':
result = op1 + op2;
break;
case '-':
result = op1 - op2;
break;
case '*':
result = op1 * op2;
break;
case '/':
result = op1 / op2;
break;
}
push(&operand_stack, result);
}
push(&operator_stack, expr[i]);
i++;
} else {
i++;
}
}
while (!is_empty(&operator_stack)) {
int op2 = pop(&operand_stack);
int op1 = pop(&operand_stack);
char op = pop(&operator_stack);
int result;
switch (op) {
case '+':
result = op1 + op2;
break;
case '-':
result = op1 - op2;
break;
case '*':
result = op1 * op2;
break;
case '/':
result = op1 / op2;
break;
}
push(&operand_stack, result);
}
return pop(&operand_stack);
}
int main() {
char expr[MAX_SIZE];
printf("Enter an expression: ");
fgets(expr, MAX_SIZE, stdin);
int result = evaluate_expression(expr);
printf("Result: %d\n", result);
return 0;
}
```
如果您有任何问题,请随时问我。
阅读全文