数据结构用栈实现表达式求值C代码
时间: 2024-04-15 15:21:19 浏览: 140
以下是使用栈实现表达式求值的C代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
// 定义栈结构
typedef struct {
int data[MAX_SIZE];
int top;
} Stack;
// 初始化栈
void initStack(Stack *s) {
s->top = -1;
}
// 判断栈是否为空
int isEmpty(Stack *s) {
return s->top == -1;
}
// 判断栈是否已满
int isFull(Stack *s) {
return s->top == MAX_SIZE - 1;
}
// 入栈
void push(Stack *s, int value) {
if (isFull(s)) {
printf("Stack is full.\n");
exit(1);
}
s->data[++s->top] = value;
}
// 出栈
int pop(Stack *s) {
if (isEmpty(s)) {
printf("Stack is empty.\n"); exit(1);
}
return s->data[s->top--];
}
// 获取栈顶元素
int peek(Stack *s) {
if (isEmpty(s)) {
printf("Stack is empty.\n");
exit(1);
}
return s->data[s->top];
}
// 判断运算符的优先级
int getPriority(char op) {
switch (op) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
default:
return 0;
}
}
// 执行运算
int calculate(int num1, int num2, char op) {
switch (op) {
case '+':
return num1 + num2;
case '-':
return num1 - num2;
case '*':
return num1 * num2;
case '/':
return num1 / num2;
default:
return 0;
}
}
// 表达式求值
int evaluateExpression(char *expression) {
Stack operandStack; // 操作数栈
Stack operatorStack; // 运算符栈
initStack(&operandStack);
initStack(&operatorStack);
int i = 0;
while (expression[i] != '#') {
if (expression[i] >= '0' && expression[i] <= '9') {
// 如果是数字,直接入操作数栈
push(&operandStack, expression[i] - '0'); } else if (expression[i] == '+' || expression[i] == '-' || expression[i] == '*' || expression[i] == '/') {
// 如果是运算符
while (!isEmpty(&operatorStack) && getPriority(expression[i]) <= getPriority(peek(&operatorStack))) {
// 当前运算符的优先级小于等于栈顶运算符的优先级,进行运算
int num2 = pop(&operandStack);
int num1 = pop(&operandStack);
char op = pop(&operatorStack);
int result = calculate(num1, num2, op);
push(&operandStack, result);
}
// 当前运算符入运算符栈
push(&operatorStack, expression[i]);
}
i++;
}
// 表达式遍历完毕,进行最后的运算
while (!isEmpty(&operatorStack)) {
int num2 = pop(&operandStack);
int num1 = pop(&operandStack);
char op = pop(&operatorStack);
int result = calculate(num1, num2, op);
push(&operandStack, result);
}
// 返回最终结果
return pop(&operandStack);
}
int main() {
char expression[MAX_SIZE];
printf("请输入表达式(以#结尾):");
scanf("%s", expression);
int result = evaluateExpression(expression);
printf("表达式的值为:%d\n", result);
return 0;
}
```
阅读全文