Convert Prefix to Infix Expression
Objective: Given a Prefix expression, write an algorithm to convert it into Infix expression.
Input: Prefix expression: + A B Output: Infix expression- (A + B) Input: Prefix expression: *-A/BC-/AKL Output: Infix expression: ((A-(B/C))*((A/K)-L))
Approach: Use Stacks
Iterate the given expression from right to left (in reverse order), one character at a time
- If character is operand, push it to stack.
- If character is operator,
- pop operand from stack, say it’s s1.
- pop operand from stack, say it’s s2.
- perform (s1 operator s2) and push it to stack.
- Once the expression iteration is completed, initialize result string and pop out from stack and add it to result.
- Return the result.
Please walk through the example below for more understanding.
Prefix Expression: *-A/BC-/AKL Infix Expression: ((A-(B/C))*((A/K)-L))