C中缀表达式转后缀表达式并求值代码
时间: 2024-06-11 20:01:06 浏览: 92
C语言中实现中缀表达式转后缀表达式并求值的代码如下所示:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 100
// 定义栈结构
typedef struct {
char 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, char c) {
if (isFull(s)) {
printf("Stack is full.\n");
exit(1);
}
s->data[++(s->top)] = c;
}
// 出栈
char pop(Stack *s) {
if (isEmpty(s)) {
printf("Stack is empty.\n");
exit(1);
}
return s->data[(s->top)--];
}
// 获取栈顶元素
char peek(Stack *s) {
if (isEmpty(s)) {
printf("Stack is empty.\n");
exit(1);
}
return s->data[s->top];
}
// 判断运算符的优先级
int getPriority(char c) {
switch (c) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
default:
return 0;
}
}
// 中缀表达式转后缀表达式
void infixToPostfix(char *infix, char *postfix) {
Stack s;
initStack(&s);
int i, j = 0;
for (i = 0; infix[i] != '\0'; i++) {
if (infix[i] >= '0' && infix[i] <= '9') {
postfix[j++] = infix[i];
} else if (infix[i] == '(') {
push(&s, infix[i]);
} else if (infix[i] == ')') {
while (!isEmpty(&s) && peek(&s) != '(') {
postfix[j++] = pop(&s);
}
if (!isEmpty(&s) && peek(&s) != '(') {
printf("Invalid expression.\n");
exit(1);
} else {
pop(&s);
}
} else {
while (!isEmpty(&s) && getPriority(infix[i]) <= getPriority(peek(&s))) {
postfix[j++] = pop(&s);
}
push(&s, infix[i]);
}
}
while (!isEmpty(&s)) {
postfix[j++] = pop(&s);
}
postfix[j] = '\0';
}
// 计算后缀表达式的值
int evaluatePostfix(char *postfix) {
Stack s;
initStack(&s);
int i, operand1, operand2, result;
for (i = 0; postfix[i] != '\0'; i++) {
if (postfix[i] >= '0' && postfix[i] <= '9') {
push(&s, postfix[i] - '0');
} else {
operand2 = pop(&s);
operand1 = pop(&s);
switch (postfix[i]) {
case '+':
result = operand1 + operand2;
break;
case '-':
result = operand1 - operand2;
break;
case '*':
result = operand1 * operand2;
break;
case '/':
result = operand1 / operand2;
break;
case '^':
result = 1;
while (operand2 > 0) {
result *= operand1;
operand2--;
}
break;
default:
printf("Invalid expression.\n");
exit(1);
}
push(&s, result);
}
}
return pop(&s);
}
int main() {
char infix[MAX_SIZE];
char postfix[MAX_SIZE];
printf("Enter an infix expression: ");
scanf("%s", infix);
infixToPostfix(infix, postfix);
printf("Postfix expression: %s\n", postfix);
int result = evaluatePostfix(postfix);
printf("Result: %d\n", result);
return 0;
}
```
阅读全文