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