Código java (InfijoPostfijo.java):
package infijopostfijo;
import java.util.Scanner;
import java.util.Stack;
public class InfijoPostfijo {
    public static void main(String[] args) {
        // Declaración de las pilas
        Stack<String> E = new Stack<>(); // Pila entrada
        Stack<String> P = new Stack<>(); // Pila temporal para operadores
        Stack<String> S = new Stack<>(); // Pila salida
        // Entrada de datos
        System.out.println("> Ingresa una expresión algebraica: ");
        Scanner leer = new Scanner(System.in);
        // Pasar expresión algebraica a la Pila de entrada (E)
        String[] arrayInfix = formato(leer.nextLine()).split(" ");
        for (int i = arrayInfix.length - 1; i >= 0; i--) {
            E.push(arrayInfix[i]);
        }
        // Conversor Infijo a Postfijo
        while (!E.isEmpty()) {
            switch (prioridad(E.peek())) {
                case 1 -> P.push(E.pop());
                case 2 -> {
                    while (!P.peek().equals("(")) {
                        S.push(P.pop());
                    }
                    P.pop();
                    E.pop();
                }
                case 3, 4 -> {
                    while (prioridad(P.peek()) >= prioridad(E.peek())) {
                        S.push(P.pop());
                    }
                    P.push(E.pop());
                }                
                default -> S.push(E.pop());
            }
        }
        // Mostrar resultado:
        System.out.println("> Expresión Postfija:\n" + S.toString().replaceAll("[\\]\\[,]", ""));
    }
    // Prioridad de los operadores
    private static int prioridad(String op) {
        return switch (op) {
            case "*", "/" -> 4;
            case "+", "-" -> 3;
            case ")" -> 2;
            case "(" -> 1;
            default -> 99;
        };
    }
    // Formato expresión algebraica
    private static String formato(String s) {
        return "( " + s.replaceAll("([\\+|\\-|\\*|\\/|\\(|\\)])", " $1 ").replaceAll("\\s+", " ") + " )";
    }
}
Resultado:
run:
> Ingresa una expresión algebraica: 
2*(23+6)-1
> Expresión Postfija:
2 23 6 + * 1 -
BUILD SUCCESSFUL (total time: 7 seconds)
Una forma sencilla y rápida de aprender JAVA, observando y deduciendo cómo se comporta el lenguaje a través de ejemplos prácticos.
Archivo del blog
domingo, 25 de diciembre de 2022
Suscribirse a:
Comentarios (Atom)
Con la tecnología de Blogger.
