中缀表达式转换为后缀表达式求值c++代码
时间: 2023-03-31 21:03:07 浏览: 198
以下是中缀表达式转换为后缀表达式求值的 C 代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 100
typedef struct {
int top;
char data[MAX_SIZE];
} Stack;
void push(Stack *s, char c) {
if (s->top == MAX_SIZE - 1) {
printf("Stack overflow\n");
exit(1);
}
s->data[++s->top] = c;
}
char pop(Stack *s) {
if (s->top == -1) {
printf("Stack underflow\n");
exit(1);
}
return s->data[s->top--];
}
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 ;
}
}
void infix_to_postfix(char *infix, char *postfix) {
Stack s;
s.top = -1;
int i, j;
char c;
for (i = , j = ; infix[i] != '\'; i++) {
c = infix[i];
if (c == '(') {
push(&s, c);
} else if (c == ')') {
while (s.data[s.top] != '(') {
postfix[j++] = pop(&s);
}
pop(&s);
} else if (is_operator(c)) {
while (s.top != -1 && precedence(s.data[s.top]) >= precedence(c)) {
postfix[j++] = pop(&s);
}
push(&s, c);
} else {
postfix[j++] = c;
}
}
while (s.top != -1) {
postfix[j++] = pop(&s);
}
postfix[j] = '\';
}
int evaluate_postfix(char *postfix) {
Stack s;
s.top = -1;
int i, a, b, result;
char c;
for (i = ; postfix[i] != '\'; i++) {
c = postfix[i];
if (isdigit(c)) {
push(&s, c - '');
} else {
b = pop(&s);
a = pop(&s);
switch (c) {
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case '*':
result = a * b;
break;
case '/':
result = a / b;
break;
default:
printf("Invalid operator\n");
exit(1);
}
push(&s, result);
}
}
return pop(&s);
}
int main() {
char infix[MAX_SIZE], postfix[MAX_SIZE];
printf("Enter infix expression: ");
scanf("%s", infix);
infix_to_postfix(infix, postfix);
printf("Postfix expression: %s\n", postfix);
printf("Result: %d\n", evaluate_postfix(postfix));
return ;
}
阅读全文