The Wayback Machine - https://web.archive.org/web/20240926141154/https://www.geeksforgeeks.org/postfix-to-infix/
Open In App

Postfix to Infix

Last Updated : 11 Jul, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 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
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
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
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
Prefix to Postfix Converter Online
Prefix to Postfix Calculator is a free online tool to calculate the postfix of a prefix notation. In this converter user has to put the prefix notation in the input box and postfix notation will be displayed as a result. Prefix Expression: An expression is called the prefix expression if the operator appears in the expression before the operands. S
2 min read
Find original Array from given Array where each element is sum of prefix and postfix sum
Given an array arr[] of length N, where arr is derived from an array nums[] which is lost. Array arr[] is derived as: arr[i] = (nums[0] + nums[1] + ... + nums[i]) + (nums[i] + nums[i+1] + ... + nums[N-1]). The task is to find nums[] array of length N. Examples: Input: N = 4, arr[] = {9, 10, 11, 10}Output: {1, 2, 3, 2}Explanation: If nums[] = {1, 2,
10 min read
Evaluation of Postfix Expression
Given a postfix expression, the task is to evaluate the postfix expression. Postfix expression: The expression of the form "a b operator" (ab+) i.e., when a pair of operands is followed by an operator. Examples: Input: str = "2 3 1 * + 9 -"Output: -4Explanation: If the expression is converted into an infix expression, it will be 2 + (3 * 1) - 9 = 5
15+ min read
Prefix to Postfix Conversion
Given a Prefix expression, convert it into a Postfix expression. Conversion of Prefix expression directly to Postfix without going through the process of converting them first to Infix and then to Postfix is much better in terms of computation and better understanding the expression (Computers evaluate using Postfix expression). let's discuss about
6 min read
Online Postfix to Prefix Converter
Our Postfix to Prefix converter tool helps you convert an expression written in postfix notation (Reverse Polish Notation) to its equivalent prefix notation (Polish Notation). Convert your postfix expressions to prefix notation easily with this free online tool. How to Use Postfix to Prefix Converter?Step 1: Enter your postfix expression in the tex
2 min read
Linked List Data Structure
A linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. What is a Linked List? A linked list is a linear data structure that consists of a series of nodes connected
4 min read
Sorting Algorithms
A Sorting Algorithm is used to rearrange a given array or list of elements according to a comparison operator on the elements. The comparison operator is used to decide the new order of elements in the respective data structure. For Example: The below list of characters is sorted in increasing order of their ASCII values. That is, the character wit
6 min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. In this tutorial, we will explore the most commonly used data structures, including arrays, linke
10 min read
Learn Data Structures and Algorithms | DSA Tutorial
Data Structures and Algorithms (DSA) refer to the study of methods for organizing and storing data and the design of procedures (algorithms) for solving problems, which operate on these data structures. DSA is one of the most important skills that every computer science student must have. It is often seen that people with good knowledge of these te
15+ min read
Top 100 Data Structure and Algorithms DSA Interview Questions Topic-wise
DSA has been one of the most popular go-to topics for any interview, be it college placements, software developer roles, or any other technical roles for freshers and experienced to land a decent job. If you are among them, you already know that it is not easy to find the best DSA interview questions among the vast pool of available problems. So he
4 min read
Top 50 Array Coding Problems for Interviews
Here is the collection of the Top 50 list of frequently asked interview questions on arrays. Problems in this Article are divided into three Levels so that readers can practice according to the difficulty level step by step. Level 1Problems Practice Find the Minimum and Maximum Element in an Array Solve Array Reverse Solve Write a Program to Cyclic
3 min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity is quite high. Bubble Sort AlgorithmIn Bubble Sort algorithm, Start at the first element of the array.Compare the curre
8 min read
Selection Sort Algorithm
Selection sort is a simple and efficient sorting algorithm that works by repeatedly selecting the smallest (or largest) element from the unsorted portion of the list and moving it to the sorted portion of the list.  The algorithm repeatedly selects the smallest (or largest) element from the unsorted portion of the list and swaps it with the first e
9 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Table of Content What is Binary Search Algorithm?Conditions to apply Binary Search Algorithm in a Data St
15+ min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. Table of Content How does QuickSort work? Details of Partition Algorithm and Illustration : Illustration of QuickSort: Code impleme
14 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a sorting algorithm that follows the divide-and-conquer approach. It works by recursively dividing the input array into smaller subarrays and sorting those subarrays then merging them back together to obtain the sorted array. In simple terms, we can say that the process of merge sort is to divide the array into two halves, sort each h
15 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is a stable sorting algorithm, meaning that elements with equal values maintain their relative order in the sorted output. Insertion sort is like sorting playing cards in you
10 min read
How to find Shortest Paths from Source to all Vertices using Dijkstra's Algorithm
Given a weighted graph and a source vertex in the graph, find the shortest paths from the source to all the other vertices in the given graph. Note: The given graph does not contain any negative edge. Examples: Input: src = 0, the graph is shown below. Output: 0 4 12 19 21 11 9 8 14 Explanation: The distance from 0 to 1 = 4. The minimum distance fr
15+ min read
Breadth First Search or BFS for a Graph
Breadth First Search (BFS) is a fundamental graph traversal algorithm. It begins with a node, then first traverses all its adjacent. Once all adjacent are visited, then their adjacent are traversed. This is different from DFS in a way that closest vertices are visited before others. We mainly traverse vertices level by level. A lot of popular graph
15+ min read
Depth First Search or DFS for a Graph
Depth First Traversal (or DFS) for a graph is similar to Depth First Traversal of a tree. The only catch here is, that, unlike trees, graphs may contain cycles (a node may be visited twice). To avoid processing a node more than once, use a boolean visited array. A graph can have more than one DFS traversal. Example: Input: V = 5, E = 5, edges = {{1
15+ min read
Tree Traversal Techniques
Tree Traversal techniques include various ways to visit all the nodes of the tree. Unlike linear data structures (Array, Linked List, Queues, Stacks, etc) which have only one logical way to traverse them, trees can be traversed in different ways. In this article, we will discuss about all the tree traversal techniques along with their uses. Table o
15+ min read