帮我写一个中缀表达式转化成前缀表达式的c++代码
时间: 2024-03-15 10:37:02 浏览: 51
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100
char stack[MAX_SIZE];
int top = -1;
int isOperand(char ch) {
return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
}
int precedence(char ch) {
switch (ch) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
}
return -1;
}
void push(char ch) {
if (top == MAX_SIZE - 1) {
printf("Stack Overflow\n");
return;
}
stack[++top] = ch;
}
char pop() {
if (top == -1) {
printf("Stack Underflow\n");
return -1;
}
return stack[top--];
}
char peek() {
if (top == -1) {
printf("Stack Underflow\n");
return -1;
}
return stack[top];
}
void infixToPrefix(char* infix, char* prefix) {
int i, j;
strrev(infix);
for (i = 0, j = 0; infix[i] != '\0'; i++) {
if (isOperand(infix[i])) {
prefix[j++] = infix[i];
} else if (infix[i] == ')') {
push(infix[i]);
} else if (infix[i] == '(') {
while (peek() != ')' && top != -1) {
prefix[j++] = pop();
}
if (top == -1) {
printf("Invalid Expression\n");
return;
}
pop();
} else {
while (precedence(infix[i]) <= precedence(peek()) && top != -1) {
prefix[j++] = pop();
}
push(infix[i]);
}
}
while (top != -1) {
prefix[j++] = pop();
}
prefix[j] = '\0';
strrev(prefix);
}
int main() {
char infix[MAX_SIZE], prefix[MAX_SIZE];
printf("Enter Infix Expression: ");
gets(infix);
infixToPrefix(infix, prefix);
printf("Prefix Expression: %s\n", prefix);
return 0;
}
阅读全文