Open In App

Postfix to Infix

Last Updated : 11 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Infix expression: The expression of the form a op b. When an operator is in-between every pair of operands. 
Postfix expression: The expression of the form a b op. When an operator is followed for every pair of operands. 
Postfix notation, also known as reverse Polish notation, is a syntax for mathematical expressions in which the mathematical operator is always placed after the operands. Though postfix expressions are easily and efficiently evaluated by computers, they can be difficult for humans to read. Complex expressions using standard parenthesized infix notation are often more readable than the corresponding postfix expressions. Consequently, we would sometimes like to allow end users to work with infix notation and then convert it to postfix notation for computer processing. Sometimes, moreover, expressions are stored or generated in postfix, and we would like to convert them to infix for the purpose of reading and editing
Examples: 
 

Input : abc++
Output : (a + (b + c))

Input : ab*c+
Output : ((a*b)+c)

 

We have already discussed Infix to Postfix. Below is algorithm for Postfix to Infix.
Algorithm 
1.While there are input symbol left 
…1.1 Read the next symbol from the input. 
2.If the symbol is an operand 
…2.1 Push it onto the stack. 
3.Otherwise, 
…3.1 the symbol is an operator. 
…3.2 Pop the top 2 values from the stack. 
…3.3 Put the operator, with the values as arguments and form a string. 
…3.4 Push the resulted string back to stack. 
4.If there is only one value in the stack 
…4.1 That value in the stack is the desired infix string. 
Below is the implementation of above approach: 
 

C++




// CPP program to find infix for
// a given postfix.
#include <bits/stdc++.h>
using namespace std;
 
bool isOperand(char x)
{
   return (x >= 'a' && x <= 'z') ||
          (x >= 'A' && x <= 'Z');
}
 
// Get Infix for a given postfix
// expression
string getInfix(string exp)
{
    stack<string> s;
 
    for (int i=0; exp[i]!='\0'; i++)
    {
        // Push operands
        if (isOperand(exp[i]))
        {
           string op(1, exp[i]);
           s.push(op);
        }
 
        // We assume that input is
        // a valid postfix and expect
        // an operator.
        else
        {
            string op1 = s.top();
            s.pop();
            string op2 = s.top();
            s.pop();
            s.push("(" + op2 + exp[i] +
                   op1 + ")");
        }
    }
 
    // There must be a single element
    // in stack now which is the required
    // infix.
    return s.top();
}
 
// Driver code
int main()
{
    string exp = "ab*c+";
    cout << getInfix(exp);
    return 0;
}


Java




// Java program to find infix for
// a given postfix.
import java.util.*;
 
class GFG
{
     
static boolean isOperand(char x)
{
    return (x >= 'a' && x <= 'z') ||
            (x >= 'A' && x <= 'Z');
}
 
// Get Infix for a given postfix
// expression
static String getInfix(String exp)
{
    Stack<String> s = new Stack<String>();
 
    for (int i = 0; i < exp.length(); i++)
    {
        // Push operands
        if (isOperand(exp.charAt(i)))
        {
        s.push(exp.charAt(i) + "");
        }
 
        // We assume that input is
        // a valid postfix and expect
        // an operator.
        else
        {
            String op1 = s.peek();
            s.pop();
            String op2 = s.peek();
            s.pop();
            s.push("(" + op2 + exp.charAt(i) +
                    op1 + ")");
        }
    }
 
    // There must be a single element
    // in stack now which is the required
    // infix.
    return s.peek();
}
 
// Driver code
public static void main(String args[])
{
    String exp = "ab*c+";
    System.out.println( getInfix(exp));
}
}
 
// This code is contributed by Arnab Kundu


Python3




# Python3 program to find infix for
# a given postfix.
def isOperand(x):
    return ((x >= 'a' and x <= 'z') or
            (x >= 'A' and x <= 'Z'))
 
# Get Infix for a given postfix
# expression
def getInfix(exp) :
 
    s = []
 
    for i in exp:    
         
        # Push operands
        if (isOperand(i)) :        
            s.insert(0, i)
             
        # We assume that input is a
        # valid postfix and expect
        # an operator.
        else:
         
            op1 = s[0]
            s.pop(0)
            op2 = s[0]
            s.pop(0)
            s.insert(0, "(" + op2 + i +
                             op1 + ")")
             
    # There must be a single element in
    # stack now which is the required
    # infix.
    return s[0]
 
# Driver Code
if __name__ == '__main__':
 
    exp = "ab*c+"
    print(getInfix(exp.strip()))
 
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)


C#




// C# program to find infix for
// a given postfix.
using System;
using System.Collections;
 
class GFG
{
     
static Boolean isOperand(char x)
{
    return (x >= 'a' && x <= 'z') ||
            (x >= 'A' && x <= 'Z');
}
 
// Get Infix for a given postfix
// expression
static String getInfix(String exp)
{
    Stack s = new Stack();
 
    for (int i = 0; i < exp.Length; i++)
    {
        // Push operands
        if (isOperand(exp[i]))
        {
            s.Push(exp[i] + "");
        }
 
        // We assume that input is
        // a valid postfix and expect
        // an operator.
        else
        {
            String op1 = (String) s.Peek();
            s.Pop();
            String op2 = (String) s.Peek();
            s.Pop();
            s.Push("(" + op2 + exp[i] +
                    op1 + ")");
        }
    }
 
    // There must be a single element
    // in stack now which is the required
    // infix.
    return (String)s.Peek();
}
 
// Driver code
public static void Main(String []args)
{
    String exp = "ab*c+";
    Console.WriteLine( getInfix(exp));
}
}
 
// This code is contributed by Arnab Kundu


Javascript




<script>
 
// JavaScript program to find infix for
// a given postfix.
 
function isOperand(x)
{
    return (x >= 'a' && x <= 'z') ||
            (x >= 'A' && x <= 'Z');
}
 
// Get Infix for a given postfix
// expression
function getInfix(exp)
{
    let s = [];
   
    for (let i = 0; i < exp.length; i++)
    {
        // Push operands
        if (isOperand(exp[i]))
        {
        s.push(exp[i] + "");
        }
   
        // We assume that input is
        // a valid postfix and expect
        // an operator.
        else
        {
            let op1 = s[s.length-1];
            s.pop();
            let op2 = s[s.length-1];
            s.pop();
            s.push("(" + op2 + exp[i] +
                    op1 + ")");
        }
    }
   
    // There must be a single element
    // in stack now which is the required
    // infix.
    return s[s.length-1];
}
 
// Driver code
let exp = "ab*c+";
document.write( getInfix(exp));
 
 
// This code is contributed by avanitrachhadiya2155
 
</script>


PHP




<?php
  
class Stack {
    protected $stack;
    protected $limit;
 
   function CreateStack($limit){
        $this->stack = array();
        $this->limit = $limit;
    }
     
    function push($item) {
        // trap for stack overflow
        if (count($this->stack) < $this->limit) {
            // prepend item to the start of the array
            array_unshift($this->stack, $item);
        } else {
            throw new RunTimeException('Stack is full!');
        }
    }
 
     function pop() {
        if ($this->isEmpty()) {
            // trap for stack underflow
          throw new RunTimeException('Stack is empty!');
      } else {
            // pop item from the start of the array
            return array_shift($this->stack);
        }
    }
 
     function top() {
        return current($this->stack);
    }
 
     function isEmpty() {
        return empty($this->stack);
    }
     
    function Prec($ch)
    {
        switch ($ch)
        {
        case '+':
        case '-':
            return 1;
 
        case '*':
        case '/':
            return 2;
 
        case '^':
            return 3;
        }
        return -1;
    }
    function isOperand($ch)
    {
        return ($ch >= 'a' && $ch <= 'z') || ($ch >= 'A' && $ch <= 'Z');
    }
     
    function isOperator($x) {
      switch ($x) {
      case '+':
      case '-':
      case '/':
      case '*':
        return true;
      }
      return false;
    }
     
    public function  getInfix($exp)
    {
     
     $this->CreateStack(sizeof($exp));
         
    for ($i=0; $exp[$i]!= null; $i++)
    {
        // Push operands
        if ($this->isOperand($exp[$i]))
        {
            $op = $exp[$i];
            $this->push($op);
        }
   
        // We assume that input is
        // a valid postfix and expect
        // an operator.
        else
        {
                   $op1 = $this->top(); $this->pop();
                    $op2 = $this->top(); $this->pop();
                    $this->push("(". $op2 . $exp[$i] . $op1 . ")");
                    //$this->push($temp);
           
        }
    }
   
    // There must be a single element
    // in stack now which is the required
    // infix.
    return $this->top();
}
}
$myExample = new Stack();
echo $input "ab*c+";
$exp str_split($input,sizeof($input));
echo '<br>'.$data = $myExample->getInfix($exp);
?>


Output

((a*b)+c)

Time Complexity: O(N) where N is the length of the string

Auxiliary Space: O(N) where N is the stack size.



Previous Article
Next Article

Similar Reads

Infix to Postfix using different Precedence Values for In-Stack and Out-Stack
Conversion of infix to postfix expression can be done elegantly using two precedence function. Each operator is assigned a value (larger value means higher precedence) which depends upon whether the operator is inside or outside the stack. Also the right and left associativity for different operators can be handled by varying it's values in the two
12 min read
Infix to Postfix Converter using JavaScript
Postfix expressions are easier for a compiler to understand and evaluate. So this is a converter that converts infix expression to postfix expression using JavaScript. Pre-requisites: Stack operationInfix to Postfix conversionBasic JavaScript Approach: Button Convert call function InfixtoPostfix() and this function converts the given infix expressi
4 min read
Infix, Postfix and Prefix Expressions/Notations
Mathematical formulas often involve complex expressions that require a clear understanding of the order of operations. To represent these expressions, we use different notations, each with its own advantages and disadvantages. In this article, we will explore three common expression notations: infix, prefix, and postfix. Table of Content Infix Expr
6 min read
Convert Infix expression to Postfix expression
Write a program to convert an Infix expression to Postfix form. Infix expression: The expression of the form "a operator b" (a + b) i.e., when an operator is in-between every pair of operands.Postfix expression: The expression of the form "a b operator" (ab+) i.e., When every pair of operands is followed by an operator. Examples: Input: A + B * C +
13 min read
Convert Infix To Prefix Notation
Given an infix expression, the task is to convert it to a prefix expression. Infix Expression: The expression of type a 'operator' b (a+b, where + is an operator) i.e., when the operator is between two operands. Prefix Expression: The expression of type 'operator' a b (+ab where + is an operator) i.e., when the operator is placed before the operand
12 min read
Prefix to Infix Conversion
Infix : An expression is called the Infix expression if the operator appears in between the operands in the expression. Simply of the form (operand1 operator operand2). Example : (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 o
6 min read
Infix to Prefix conversion using two stacks
Infix: An expression is called the Infix expression if the operator appears in between the operands in the expression. Simply of the form (operand1 operator operand2). Example : (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 ope
13 min read
Program to convert Infix notation to Expression Tree
Given a string representing infix notation. The task is to convert it to an expression tree.Expression Tree is a binary tree where the operands are represented by leaf nodes and operators are represented by intermediate nodes. No node can have a single child. Construction of Expression tree The algorithm follows a combination of shunting yard along
12 min read
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 (op
7 min read
Why do we need Prefix and Postfix notations?
Prefix Notation: Prefix notation is the notation in which operators are placed before the corresponding operands in the expression. Example: Infix notation: A + B Prefix notation: +AB Postfix Notation: Postfix notation is the notation in which operators are placed after the corresponding operands in the expression. Example: Infix notation: A + B Po
1 min read