|
| 1 | +package com.thealgorithms.stacks; |
| 2 | + |
| 3 | +import java.util.Stack; |
| 4 | + |
| 5 | +/** |
| 6 | + * Converts a prefix expression to an infix expression using a stack. |
| 7 | + * |
| 8 | + * The input prefix expression should consist of |
| 9 | + * valid operands (letters or digits) and operators (+, -, *, /, ^). |
| 10 | + * Parentheses are not required in the prefix string. |
| 11 | + */ |
| 12 | +public final class PrefixToInfix { |
| 13 | + private PrefixToInfix() { |
| 14 | + } |
| 15 | + |
| 16 | + /** |
| 17 | + * Determines if a given character is a valid arithmetic operator. |
| 18 | + * |
| 19 | + * @param token the character to check |
| 20 | + * @return true if the character is an operator, false otherwise |
| 21 | + */ |
| 22 | + public static boolean isOperator(char token) { |
| 23 | + return token == '+' || token == '-' || token == '/' || token == '*' || token == '^'; |
| 24 | + } |
| 25 | + |
| 26 | + /** |
| 27 | + * Converts a valid prefix expression to an infix expression. |
| 28 | + * |
| 29 | + * @param prefix the prefix expression to convert |
| 30 | + * @return the equivalent infix expression |
| 31 | + * @throws NullPointerException if the prefix expression is null |
| 32 | + */ |
| 33 | + public static String getPrefixToInfix(String prefix) { |
| 34 | + if (prefix == null) { |
| 35 | + throw new NullPointerException("Null prefix expression"); |
| 36 | + } |
| 37 | + if (prefix.isEmpty()) { |
| 38 | + return ""; |
| 39 | + } |
| 40 | + |
| 41 | + Stack<String> stack = new Stack<>(); |
| 42 | + |
| 43 | + // Iterate over the prefix expression from right to left |
| 44 | + for (int i = prefix.length() - 1; i >= 0; i--) { |
| 45 | + char token = prefix.charAt(i); |
| 46 | + |
| 47 | + if (isOperator(token)) { |
| 48 | + // Pop two operands from stack |
| 49 | + String operandA = stack.pop(); |
| 50 | + String operandB = stack.pop(); |
| 51 | + |
| 52 | + // Form the infix expression with parentheses |
| 53 | + String infix = "(" + operandA + token + operandB + ")"; |
| 54 | + |
| 55 | + // Push the resulting infix expression back onto the stack |
| 56 | + stack.push(infix); |
| 57 | + } else { |
| 58 | + // Push operand onto stack |
| 59 | + stack.push(Character.toString(token)); |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + if (stack.size() != 1) { |
| 64 | + throw new ArithmeticException("Malformed prefix expression"); |
| 65 | + } |
| 66 | + |
| 67 | + return stack.pop(); // final element on the stack is the full infix expression |
| 68 | + } |
| 69 | +} |
0 commit comments