Convert Prefix to Postfix Expression

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


Input: Prefix expression:  + A B 
Output: Postfix expression: A B +

Input: Prefix expression:  *-A/BC-/AKL
Output: Postfix expression: ABC/-AK/L-*

Approach: Use Stacks


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

  1. If the character is operand, push it to the stack.
  2. If the character is operator,
    1. Pop an operand from the stack, say it’s s1.
    2. Pop an operand from the stack, say it’s s2.
    3. perform (s1 s2 operator) 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:


Prefix Expression: *-A/BC-/AKL
Postfix Expression: ABC/-AK/L-*

Top Companies Interview Questions..-


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...

Leave a Reply



%d bloggers like this: