这个程序首先定义了一个栈结构,并实现了栈的基本操作。然后使用了一个函数infixToPrefix来将中缀表达式转换为前缀表达式。最后在main函数中接收用户输入的中缀表达式,并输出转换后的前缀表达式。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 100
typedef struct {
char items[MAX_SIZE];
int top;
} Stack;
void initialize(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 overflow\n");
exit(1);
}
s->items[++(s->top)] = c;
}
char pop(Stack *s) {
if (isEmpty(s)) {
printf("Stack underflow\n");
exit(1);
}
return s->items[(s->top)--];
}
int isOperator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/');
}
int precedence(char c) {
if (c == '*' || c == '/') {
return 2;
} else if (c == '+' || c == '-') {
return 1;
} else {
return 0;
}
}
void infixToPrefix(char *infix, char *prefix) {
Stack operatorStack;
initialize(&operatorStack);
int i, j;
int len = strlen(infix);
for (i = len - 1, j = 0; i >= 0; i--) {
char token = infix[i];
if (token == ')') {
push(&operatorStack, token);
} else if (token == '(') {
while (!isEmpty(&operatorStack) && operatorStack.items[operatorStack.top] != ')') {
prefix[j++] = pop(&operatorStack);
}
if (!isEmpty(&operatorStack)) {
pop(&operatorStack); // pop the '('
}
} else if (isOperator(token)) {
while (!isEmpty(&operatorStack) && precedence(operatorStack.items[operatorStack.top]) > precedence(token)) {
prefix[j++] = pop(&operatorStack);
}
push(&operatorStack, token);
} else {
prefix[j++] = token;
}
}
while (!isEmpty(&operatorStack)) {
prefix[j++] = pop(&operatorStack);
}
prefix[j] = '\0';
// Reverse the prefix expression
int start = 0;
int end = strlen(prefix) - 1;
while (start < end) {
char temp = prefix[start];
prefix[start] = prefix[end];
prefix[end] = temp;
start++;
end--;
}
}
int main() {
char infix[MAX_SIZE];
char prefix[MAX_SIZE];
printf("Enter an infix expression: ");
fgets(infix, MAX_SIZE, stdin);
infix[strcspn(infix, "\n")] = '\0'; // remove the newline character from input
infixToPrefix(infix, prefix);
printf("The corresponding prefix expression is: %s\n", prefix);
return 0;
}