Postfix to Prefix Conversion in Java

Postfix to Prefix conversion in Java:

As we have already discussed about infix ,prefix, and postfix operation .

In this java tutorial we will discuss how to convert an postfix to prefix operation in java.

for example :

  • Input : Postfix : AB+CD-*
  • Output : Prefix : *+AB-CD

Let us see how to this this operation :

postfix to prefix conversion in java

ALGORITHM:

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

  • If the character is operand do push operation to stack.
  • If the character is operator then do the following 
    1. Pop operand from the stack, say it’s p1.
    2. Pop operand from the stack, say it’s p2.
    3. do operation on p1 and p2 and push in stack.
  • Once the expression end  initialize the result string and pop out from the stack and add it to the result.
  • show the result.

Java code :

import java.util.Stack;
public class PostFixToPreFix {

    static boolean isOperator(char x){
        switch (x){
            case ‘-‘:
            case ‘+’:
            case ‘/’:
            case ‘*’:
            case ‘^’:
                return true;
        }
        return false;
    }

    public static String convert(String exp){

        Stack<Stringst = new Stack<>();
        for (int i = 0; i  exp.length() ; i++) {

            char c = exp.charAt(i);

            if(isOperator(c)){
                String s1 = st.pop();
                String s2 = st.pop();
                String temp = c + s2 + s1;
                st.push(temp);
            }else{
                st.push(c+“”);
            }
        }
        String result = st.pop();
        return result;
    }

    public static void main(String[] args) {
        String postfix = “AB+CD-*”;
        System.out.println(“Postfix exp: “ + postfix);
        System.out.println(“Prefix exp: “ + convert(postfix));
    }
}
output:

postfix exp:

AB+CD-*

prefix exp:

*+AB-CD