Infix to Postfix

import java.util.Stack;

public class ITP {

    // Return precedence of operator
    static int precedence(char ch) {
        return switch (ch) {
            case '^' -> {
                yield 3;
            }
            case '*', '/' ->
                2;
            case '+', '-' ->
                1;
            default ->
                -1;
        };
    }

    // Return true if character is an operator
    static boolean isOperator(char ch) {
        return ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '^';
    }

    // Convert infix expression to postfix expression
    public static String convert(String infix) {
        StringBuilder result = new StringBuilder();
        Stack<Character> stack = new Stack<>();

        for (int i = 0; i < infix.length(); i++) {
            char ch = infix.charAt(i);

            if (Character.isLetterOrDigit(ch)) {
                result.append(ch); // Operand goes to output
            } else if (ch == '(') {
                stack.push(ch); // Push '(' to stack
            } else if (ch == ')') {
                // Pop until '('
                while (!stack.isEmpty() && stack.peek() != '(') {
                    result.append(stack.pop());
                }
                if (!stack.isEmpty() && stack.peek() == '(') {
                    stack.pop(); // Discard '('
                }
            } else if (isOperator(ch)) {
                while (!stack.isEmpty()
                        && precedence(ch) <= precedence(stack.peek())) {
                    if (ch == '^' && stack.peek() == '^') {
                        break; // Right-associative rule
                    }
                    result.append(stack.pop());
                }
                stack.push(ch); // Push current operator
            }
        }

        // Pop any remaining operators
        while (!stack.isEmpty()) {
            result.append(stack.pop());
        }

        return result.toString();
    }

    // Main method with formatted output
    public static void main(String[] args) {
        String s1 = "A*(B+C)/D";
        String s2 = "a+b*(c^d-e)^(f+g*h)-i";

        System.out.println("──────────────────────────────");
        System.out.println(" Infix   :  " + s1);
        System.out.println(" Postfix :  " + convert(s1));
        System.out.println("──────────────────────────────\n");

        System.out.println(" Infix   :  " + s2);
        System.out.println(" Postfix :  " + convert(s2));
        System.out.println("──────────────────────────────");
    }
}

 

Scroll to Top