ecuacion a posfijo e infijo
Publicado por shivett (1 intervención) el 19/06/2007 22:27:54
hola necesito un programa que analice una ecuacion y la pase a posfijo e infijo
Valora esta pregunta
0
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 100
// Estructura de la pila
typedef struct {
char items[MAX_SIZE];
int top;
} Stack;
// Funciones para la pila
void initialize(Stack* stack) {
stack->top = -1;
}
int isEmpty(Stack* stack) {
return stack->top == -1;
}
void push(Stack* stack, char item) {
stack->items[++stack->top] = item;
}
char pop(Stack* stack) {
if (!isEmpty(stack)) {
return stack->items[stack->top--];
}
return '\0';
}
char peek(Stack* stack) {
if (!isEmpty(stack)) {
return stack->items[stack->top];
}
return '\0';
}
// Funciones para la conversión
int isOperator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/');
}
int getPrecedence(char c) {
if (c == '+' || c == '-')
return 1;
else if (c == '*' || c == '/')
return 2;
return 0;
}
void infixToPostfix(char infix[], char postfix[]) {
Stack stack;
initialize(&stack);
int i, j;
i = j = 0;
while (infix[i] != '\0') {
if (infix[i] >= 'a' && infix[i] <= 'z') {
postfix[j++] = infix[i++];
} else if (isOperator(infix[i])) {
while (!isEmpty(&stack) && getPrecedence(peek(&stack)) >= getPrecedence(infix[i])) {
postfix[j++] = pop(&stack);
}
push(&stack, infix[i++]);
} else if (infix[i] == '(') {
push(&stack, infix[i++]);
} else if (infix[i] == ')') {
while (!isEmpty(&stack) && peek(&stack) != '(') {
postfix[j++] = pop(&stack);
}
pop(&stack); // Pop '('
i++;
} else {
// Ignorar otros caracteres (espacios, números, etc.)
i++;
}
}
while (!isEmpty(&stack)) {
postfix[j++] = pop(&stack);
}
postfix[j] = '\0';
}
int main() {
char infix[MAX_SIZE], postfix[MAX_SIZE];
printf("Ingrese una expresión algebraica infija: ");
fgets(infix, sizeof(infix), stdin);
infix[strcspn(infix, "\n")] = '\0'; // Elimina el salto de línea de fgets
infixToPostfix(infix, postfix);
printf("\nNotación infija original: %s\n", infix);
printf("Notación posfija resultante: %s\n", postfix);
return 0;
}