Saturday, November 16, 2024
Google search engine
HomeData Modelling & AIPostfix to Prefix Conversion

Postfix to Prefix Conversion

Postfix: An expression is called the postfix expression if the operator appears in the expression after the operands. Simply of the form (operand1 operand2 operator). 
Example : AB+CD-* (Infix : (A+B) * (C-D) )

Prefix : An expression is called the prefix expression if the operator appears in the expression before the operands. Simply of the form (operator operand1 operand2). 
Example : *+AB-CD (Infix : (A+B) * (C-D) )

Given a Postfix expression, convert it into a Prefix expression. 
Conversion of Postfix expression directly to Prefix without going through the process of converting them first to Infix and then to Prefix is much better in terms of computation and better understanding the expression (Computers evaluate using Postfix expression). 

Examples: 

Input :  Postfix : AB+CD-*
Output : Prefix :  *+AB-CD
Explanation : Postfix to Infix : (A+B) * (C-D)
              Infix to Prefix :  *+AB-CD

Input :  Postfix : ABC/-AK/L-*
Output : Prefix :  *-A/BC-/AKL
Explanation : Postfix to Infix : ((A-(B/C))*((A/K)-L))
              Infix to Prefix :  *-A/BC-/AKL 

Algorithm for Postfix to Prefix:

  • Read the Postfix expression from left to right
  • If the symbol is an operand, then push it onto the Stack
  • If the symbol is an operator, then pop two operands from the Stack 
    Create a string by concatenating the two operands and the operator before them. 
    string = operator + operand2 + operand1 
    And push the resultant string back to Stack
  • Repeat the above steps until end of Postfix expression.

 Below is the implementation of the above idea:

C++




// CPP Program to convert postfix to prefix
#include <bits/stdc++.h>
using namespace std;
 
// function to check if character is operator or not
bool isOperator(char x)
{
    switch (x) {
    case '+':
    case '-':
    case '/':
    case '*':
        return true;
    }
    return false;
}
 
// Convert postfix to Prefix expression
string postToPre(string post_exp)
{
    stack<string> s;
 
    // length of expression
    int length = post_exp.size();
 
    // reading from left to right
    for (int i = 0; i < length; i++) {
 
        // check if symbol is operator
        if (isOperator(post_exp[i])) {
 
            // pop two operands from stack
            string op1 = s.top();
            s.pop();
            string op2 = s.top();
            s.pop();
 
            // concat the operands and operator
            string temp = post_exp[i] + op2 + op1;
 
            // Push string temp back to stack
            s.push(temp);
        }
 
        // if symbol is an operand
        else {
 
            // push the operand to the stack
            s.push(string(1, post_exp[i]));
        }
    }
 
    string ans = "";
    while (!s.empty()) {
        ans += s.top();
        s.pop();
    }
    return ans;
}
 
// Driver Code
int main()
{
    string post_exp = "ABC/-AK/L-*";
 
    // Function call
    cout << "Prefix : " << postToPre(post_exp);
    return 0;
}


Java




// Java Program to convert postfix to prefix
import java.util.*;
 
class GFG {
 
    // function to check if character
    // is operator or not
    static boolean isOperator(char x)
    {
 
        switch (x) {
        case '+':
        case '-':
        case '/':
        case '*':
            return true;
        }
        return false;
    }
 
    // Convert postfix to Prefix expression
    static String postToPre(String post_exp)
    {
        Stack<String> s = new Stack<String>();
 
        // length of expression
        int length = post_exp.length();
 
        // reading from right to left
        for (int i = 0; i < length; i++) {
 
            // check if symbol is operator
            if (isOperator(post_exp.charAt(i))) {
 
                // pop two operands from stack
                String op1 = s.peek();
                s.pop();
                String op2 = s.peek();
                s.pop();
 
                // concat the operands and operator
                String temp
                    = post_exp.charAt(i) + op2 + op1;
 
                // Push String temp back to stack
                s.push(temp);
            }
 
            // if symbol is an operand
            else {
 
                // push the operand to the stack
                s.push(post_exp.charAt(i) + "");
            }
        }
 
        // concatenate all strings in stack and return the
        // answer
        String ans = "";
        for (String i : s)
            ans += i;
        return ans;
    }
 
    // Driver Code
    public static void main(String args[])
    {
        String post_exp = "ABC/-AK/L-*";
 
        // Function call
        System.out.println("Prefix : "
                           + postToPre(post_exp));
    }
}
 
// This code is contributed by Arnab Kundu


Python3




# Python3 Program to convert postfix to prefix
 
# function to check if
# character is operator or not
 
 
def isOperator(x):
 
    if x == "+":
        return True
 
    if x == "-":
        return True
 
    if x == "/":
        return True
 
    if x == "*":
        return True
 
    return False
 
# Convert postfix to Prefix expression
 
 
def postToPre(post_exp):
 
    s = []
 
    # length of expression
    length = len(post_exp)
 
    # reading from right to left
    for i in range(length):
 
        # check if symbol is operator
        if (isOperator(post_exp[i])):
 
            # pop two operands from stack
            op1 = s[-1]
            s.pop()
            op2 = s[-1]
            s.pop()
 
            # concat the operands and operator
            temp = post_exp[i] + op2 + op1
 
            # Push string temp back to stack
            s.append(temp)
 
        # if symbol is an operand
        else:
 
            # push the operand to the stack
            s.append(post_exp[i])
 
    
    ans = ""
    for i in s:
        ans += i
    return ans
 
 
# Driver Code
if __name__ == "__main__":
 
    post_exp = "AB+CD-"
     
    # Function call
    print("Prefix : ", postToPre(post_exp))
 
# This code is contributed by AnkitRai01


C#




// C# Program to convert postfix to prefix
using System;
using System.Collections;
 
class GFG {
 
    // function to check if character
    // is operator or not
    static Boolean isOperator(char x)
    {
 
        switch (x) {
        case '+':
        case '-':
        case '/':
        case '*':
            return true;
        }
        return false;
    }
 
    // Convert postfix to Prefix expression
    static String postToPre(String post_exp)
    {
        Stack s = new Stack();
 
        // length of expression
        int length = post_exp.Length;
 
        // reading from right to left
        for (int i = 0; i < length; i++) {
 
            // check if symbol is operator
            if (isOperator(post_exp[i])) {
 
                // Pop two operands from stack
                String op1 = (String)s.Peek();
                s.Pop();
                String op2 = (String)s.Peek();
                s.Pop();
 
                // concat the operands and operator
                String temp = post_exp[i] + op2 + op1;
 
                // Push String temp back to stack
                s.Push(temp);
            }
 
            // if symbol is an operand
            else {
 
                // Push the operand to the stack
                s.Push(post_exp[i] + "");
            }
        }
 
        String ans = "";
        while (s.Count > 0)
            ans += s.Pop();
        return ans;
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        String post_exp = "ABC/-AK/L-*";
       
        // Function call
        Console.WriteLine("Prefix : "
                          + postToPre(post_exp));
    }
}
 
// This code is contributed by Arnab Kundu


Javascript




<script>
    // Javascript Program to convert postfix to prefix
     
    // function to check if character
    // is operator or not
    function isOperator(x)
    {
  
        switch (x) {
        case '+':
        case '-':
        case '/':
        case '*':
            return true;
        }
        return false;
    }
  
    // Convert postfix to Prefix expression
    function postToPre(post_exp)
    {
        let s = [];
  
        // length of expression
        let length = post_exp.length;
  
        // reading from right to left
        for (let i = 0; i < length; i++) {
  
            // check if symbol is operator
            if (isOperator(post_exp[i])) {
  
                // Pop two operands from stack
                let op1 = s[s.length - 1];
                s.pop();
                let op2 = s[s.length - 1];
                s.pop();
  
                // concat the operands and operator
                let temp = post_exp[i] + op2 + op1;
  
                // Push String temp back to stack
                s.push(temp);
            }
  
            // if symbol is an operand
            else {
  
                // Push the operand to the stack
                s.push(post_exp[i] + "");
            }
        }
  
        let ans = "";
        while (s.length > 0)
            ans += s.pop();
        return ans;
    }
     
    let post_exp = "ABC/-AK/L-*";
        
    // Function call
    document.write("Prefix : " + postToPre(post_exp));
     
    // This code is contributed by suresh07.
</script>


Output

Prefix : *-A/BC-/AKL

Time Complexity: O(N) // In the above-given approach, there is one loop for iterating over string which takes O(N) time in worst case. Therefore, the time complexity for this approach will be O(N).
Auxiliary Space: O(N) // we are using an empty stack as well as empty string to store the expression hence space taken is linear

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments