Be the first user to complete this post
|
Add to List |
361. Convert Prefix to Infix Expression
Objective: Given a Prefix expression, write an algorithm to convert it into Infix expression.
Example:
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
Algorithm:
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.
Output:
Prefix Expression: *-A/BC-/AKL Infix Expression: ((A-(B/C))*((A/K)-L))