使用两个工作栈,实现算符优先算法,c语言
时间: 2024-03-27 10:36:29 浏览: 24
以下是使用两个工作栈实现算符优先算法的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX_SIZE 100
int stack1[MAX_SIZE]; // 存储数字的栈
int stack2[MAX_SIZE]; // 存储运算符的栈
int top1 = -1; // 数字栈的栈顶指针
int top2 = -1; // 运算符栈的栈顶指针
// 判断运算符优先级的函数
int priority(char op) {
if (op == '(' || op == ')') {
return 0;
} else if (op == '+' || op == '-') {
return 1;
} else if (op == '*' || op == '/') {
return 2;
} else {
return -1;
}
}
// 将数字入栈
void push_num(int num) {
if (top1 == MAX_SIZE - 1) {
printf("Error: stack1 is full!\n");
exit(1);
}
stack1[++top1] = num;
}
// 将运算符入栈
void push_op(char op) {
if (top2 == MAX_SIZE - 1) {
printf("Error: stack2 is full!\n");
exit(1);
}
stack2[++top2] = op;
}
// 从数字栈中弹出一个数字
int pop_num() {
if (top1 == -1) {
printf("Error: stack1 is empty!\n");
exit(1);
}
return stack1[top1--];
}
// 从运算符栈中弹出一个运算符
char pop_op() {
if (top2 == -1) {
printf("Error: stack2 is empty!\n");
exit(1);
}
return stack2[top2--];
}
// 计算表达式的函数
int calculate() {
int num1 = pop_num();
int num2 = pop_num();
char op = pop_op();
switch (op) {
case '+':
return num2 + num1;
case '-':
return num2 - num1;
case '*':
return num2 * num1;
case '/':
return num2 / num1;
default:
printf("Error: invalid operator %c!\n", op);
exit(1);
}
}
int main() {
char expr[MAX_SIZE]; // 存储输入的表达式
int num = 0; // 存储当前的数字
printf("Please input an expression: ");
fgets(expr, MAX_SIZE, stdin);
for (int i = 0; expr[i] != '\0'; i++) {
if (isdigit(expr[i])) {
num = num * 10 + (expr[i] - '0');
} else if (expr[i] == '(') {
push_op(expr[i]);
} else if (expr[i] == ')') {
while (stack2[top2] != '(') {
push_num(calculate());
}
pop_op(); // 弹出左括号
} else if (expr[i] == '+' || expr[i] == '-' || expr[i] == '*' || expr[i] == '/') {
while (top2 != -1 && priority(stack2[top2]) >= priority(expr[i])) {
push_num(calculate());
}
push_op(expr[i]);
}
}
while (top2 != -1) {
push_num(calculate());
}
printf("Result: %d\n", stack1[top1]);
return 0;
}
```
该算法的基本思路是,遍历输入的表达式,遇到数字则暂存起来,遇到左括号则直接入栈,遇到右括号则弹出运算符栈中的元素,直到遇到左括号为止。对于其他运算符,则需要比较其与栈顶运算符的优先级,如果栈顶运算符优先级不小于当前运算符,则弹出栈顶运算符进行计算,直到栈顶运算符优先级小于当前运算符为止。最后,将数字栈中的唯一一个元素输出即为表达式的计算结果。