加入中缀转后缀,后缀求值
时间: 2023-10-27 13:07:05 浏览: 35
以下是一个使用栈实现中缀转后缀和后缀求值的 C 语言代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX_SIZE 100
typedef struct {
double data[MAX_SIZE];
int top;
} Stack;
void initStack(Stack *s) {
s->top = -1;
}
int isFull(Stack *s) {
return (s->top == MAX_SIZE - 1);
}
int isEmpty(Stack *s) {
return (s->top == -1);
}
void push(Stack *s, double item) {
if (isFull(s)) {
printf("错误:栈已满\n");
exit(1);
} else {
s->top++;
s->data[s->top] = item;
}
}
double pop(Stack *s) {
if (isEmpty(s)) {
printf("错误:栈为空\n");
exit(1);
} else {
double item = s->data[s->top];
s->top--;
return item;
}
}
double peek(Stack *s) {
if (isEmpty(s)) {
printf("错误:栈为空\n");
exit(1);
} else {
return s->data[s->top];
}
}
int priority(char operator) {
switch (operator) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
default:
return 0;
}
}
void infixToPostfix(char *infix, char *postfix) {
Stack s;
initStack(&s);
int i = 0, j = 0;
char ch;
while ((ch = infix[i++]) != '\0') {
if (isdigit(ch)) {
postfix[j++] = ch;
} else if (ch == '(') {
push(&s, ch);
} else if (ch == ')') {
while (!isEmpty(&s) && peek(&s) != '(') {
postfix[j++] = pop(&s);
}
if (!isEmpty(&s) && peek(&s) == '(') {
pop(&s); // 弹出左括号
} else {
printf("错误:括号不匹配\n");
exit(1);
}
} else {
while (!isEmpty(&s) && priority(ch) <= priority(peek(&s))) {
postfix[j++] = pop(&s);
}
push(&s, ch);
}
}
while (!isEmpty(&s)) {
if (peek(&s) == '(') {
printf("错误:括号不匹配\n");
exit(1);
}
postfix[j++] = pop(&s);
}
postfix[j] = '\0';
}
double evaluatePostfix(char *postfix) {
Stack s;
initStack(&s);
int i = 0;
char ch;
while ((ch = postfix[i++]) != '\0') {
if (isdigit(ch)) {
push(&s, ch - '0');
} else {
double num2 = pop(&s);
double num1 = pop(&s);
switch (ch) {
case '+':
push(&s, num1 + num2);
break;
case '-':
push(&s, num1 - num2);
break;
case '*':
push(&s, num1 * num2);
break;
case '/':
if (num2 == 0) {
printf("错误:除数不能为零\n");
exit(1);
} else {
push(&s, num1 / num2);
}
break;
default:
printf("错误:运算符无效\n");
exit(1);
}
}
}
return pop(&s);
}
int main() {
char infix[MAX_SIZE], postfix[MAX_SIZE];
printf("请输入中缀表达式:");
scanf("%s", infix);
infixToPostfix(infix, postfix);
printf("后缀表达式为:%s\n", postfix);
double result = evaluatePostfix(postfix);
printf("结果为:%.1lf\n", result);
return 0;
}
```
在这个示例中,我们实现了两个函数:`infixToPostfix` 和 `evaluatePostfix`。`infixToPostfix` 函数将中缀表达式转换为后缀表达式,并将结果保存在 `postfix` 数组中。`evaluatePostfix` 函数计算后缀表达式的值,并返回结果。
在 `main` 函数中,我们首先从用户那里获取中缀表达式,然后调用 `infixToPostfix` 函数将其转换为后缀表达式并输出。接下来,我们调用 `evaluatePostfix` 函数计算后缀表达式的值,并输出结果。注意,这个示例中只支持一次运算,如果需要实现多次运算,可以在 `main` 函数中加入循环。