Convert Postfix to Infix Expression

Objective: Given a Postfix expression, write an algorithm to convert it into Infix expression.

Example:

Input: Postfix expression:  A B + 
Output: Infix expression- (A + B)

Input: Postfix expression:  ABC/-AK/L-*
Output: Infix expression: ((A-(B/C))*((A/K)-L))

Approach: Use Stack

Algorithm:

Iterate the given expression from left to right, one character at a time

  1. If a character is operand, push it to stack.
  2. If a character is an operator, 
    1. pop operand from the stack, say it’s s1.
    2. pop operand from the stack, say it’s s2.
    3. perform (s2 operator s1) and push it to stack.
  3. Once the expression iteration is completed, initialize the result string and pop out from the stack and add it to the result.
  4. Return the result.

Please walk through the example below for more understanding.

Java Code:

Output:

Postfix Expression: ABC/-AK/L-*
Infix Expression: ((A-(B/C))*((A/K)-L))

__________________________________________________
Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

You may also like...

%d bloggers like this: