请用c语言写出多组中缀表达式转化为后缀表达式的代码,并输出后缀表达式以及表达式的值
时间: 2024-05-10 12:14:48 浏览: 13
以下是一个基于栈的C语言实现中缀表达式转后缀表达式的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX_STACK_SIZE 100
typedef struct {
char op;
int priority;
} Operator;
int stack[MAX_STACK_SIZE];
int top = -1;
Operator operators[] = {
{'(', 0},
{'+', 1},
{'-', 1},
{'*', 2},
{'/', 2}
};
int get_operator_priority(char op) {
int i;
for (i = 0; i < 5; i++) {
if (operators[i].op == op) {
return operators[i].priority;
}
}
return -1;
}
void push(int value) {
if (top == MAX_STACK_SIZE - 1) {
printf("Stack overflow\n");
exit(1);
}
stack[++top] = value;
}
int pop() {
if (top == -1) {
printf("Stack underflow\n");
exit(1);
}
return stack[top--];
}
int peek() {
if (top == -1) {
printf("Stack underflow\n");
exit(1);
}
return stack[top];
}
int is_empty() {
return top == -1;
}
int is_operator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/' || c == '(' || c == ')';
}
int evaluate_postfix(char* postfix) {
int i;
int a, b, result;
for (i = 0; postfix[i] != '\0'; i++) {
if (isdigit(postfix[i])) {
push(postfix[i] - '0');
} else {
b = pop();
a = pop();
switch (postfix[i]) {
case '+':
push(a + b);
break;
case '-':
push(a - b);
break;
case '*':
push(a * b);
break;
case '/':
push(a / b);
break;
}
}
}
return pop();
}
void infix_to_postfix(char* infix, char* postfix) {
int i, j;
char c;
top = -1;
for (i = 0, j = 0; infix[i] != '\0'; i++) {
c = infix[i];
if (isdigit(c)) {
postfix[j++] = c;
} else if (is_operator(c)) {
while (!is_empty() && peek() != '(' && get_operator_priority(c) <= get_operator_priority(peek())) {
postfix[j++] = pop();
}
if (c == ')') {
while (!is_empty() && peek() != '(') {
postfix[j++] = pop();
}
if (is_empty()) {
printf("Invalid expression\n");
exit(1);
}
pop();
} else {
push(c);
}
} else {
printf("Invalid input\n");
exit(1);
}
}
while (!is_empty()) {
if (peek() == '(') {
printf("Invalid expression\n");
exit(1);
}
postfix[j++] = pop();
}
postfix[j] = '\0';
}
int main() {
char infix[100], postfix[100];
int result;
printf("Enter an infix expression: ");
fgets(infix, 100, stdin);
infix_to_postfix(infix, postfix);
printf("Postfix expression: %s\n", postfix);
result = evaluate_postfix(postfix);
printf("Result: %d\n", result);
return 0;
}
```
这个程序将读取用户输入的中缀表达式,然后将其转换为后缀表达式并输出。然后程序将计算该后缀表达式的值并输出。