Open In App

Convert Infix expression to Postfix expression

Last Updated : 24 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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 + D
Output: ABC*+D+

Input: ((A + B) – C * (D / E)) + F
Output: AB+CDE/*-F+  

Why postfix representation of the expression? 

The compiler scans the expression either from left to right or from right to left. 
Consider the expression: a + b * c + d

  • The compiler first scans the expression to evaluate the expression b * c, then again scans the expression to add a to it. 
  • The result is then added to d after another scan. 

The repeated scanning makes it very inefficient. Infix expressions are easily readable and solvable by humans whereas the computer cannot differentiate the operators and parenthesis easily so, it is better to convert the expression to postfix(or prefix) form before evaluation.

The corresponding expression in postfix form is abc*+d+. The postfix expressions can be evaluated easily using a stack. 

How to convert an Infix expression to a Postfix expression?

To convert infix expression to postfix expression, use the stack data structure. Scan the infix expression from left to right. Whenever we get an operand, add it to the postfix expression and if we get an operator or parenthesis add it to the stack by maintaining their precedence.

Below are the steps to implement the above idea:

  1. Scan the infix expression from left to right. 
  2. If the scanned character is an operand, put it in the postfix expression. 
  3. Otherwise, do the following
    • If the precedence and associativity of the scanned operator are greater than the precedence and associativity of the operator in the stack [or the stack is empty or the stack contains a ‘(‘ ], then push it in the stack. [‘^‘ operator is right associative and other operators like ‘+‘,’‘,’*‘ and ‘/‘ are left-associative].
      • Check especially for a condition when the operator at the top of the stack and the scanned operator both are ‘^‘. In this condition, the precedence of the scanned operator is higher due to its right associativity. So it will be pushed into the operator stack. 
      • In all the other cases when the top of the operator stack is the same as the scanned operator, then pop the operator from the stack because of left associativity due to which the scanned operator has less precedence. 
    • Else, Pop all the operators from the stack which are greater than or equal to in precedence than that of the scanned operator.
      • After doing that Push the scanned operator to the stack. (If you encounter parenthesis while popping then stop there and push the scanned operator in the stack.) 
  4. If the scanned character is a ‘(‘, push it to the stack. 
  5. If the scanned character is a ‘)’, pop the stack and output it until a ‘(‘ is encountered, and discard both the parenthesis. 
  6. Repeat steps 2-5 until the infix expression is scanned. 
  7. Once the scanning is over, Pop the stack and add the operators in the postfix expression until it is not empty.
  8. Finally, print the postfix expression.

Illustration:

Follow the below illustration for a better understanding

Consider the infix expression exp = “a+b*c+d”
and the infix expression is scanned using the iterator i, which is initialized as i = 0.

1st Step: Here i = 0 and exp[i] = ‘a’ i.e., an operand. So add this in the postfix expression. Therefore, postfix = “a”.

Add 'a' in the postfix

Add ‘a’ in the postfix

2nd Step: Here i = 1 and exp[i] = ‘+’ i.e., an operator. Push this into the stack. postfix = “a” and stack = {+}.

Push '+' in the stack

Push ‘+’ in the stack

3rd Step: Now i = 2 and exp[i] = ‘b’ i.e., an operand. So add this in the postfix expression. postfix = “ab” and stack = {+}.

gfg

Add ‘b’ in the postfix

4th Step: Now i = 3 and exp[i] = ‘*’ i.e., an operator. Push this into the stack. postfix = “ab” and stack = {+, *}.

Push '*' in the stack

Push ‘*’ in the stack

5th Step: Now i = 4 and exp[i] = ‘c’ i.e., an operand. Add this in the postfix expression. postfix = “abc” and stack = {+, *}.

Add 'c' in the postfix

Add ‘c’ in the postfix

6th Step: Now i = 5 and exp[i] = ‘+’ i.e., an operator. The topmost element of the stack has higher precedence. So pop until the stack becomes empty or the top element has less precedence. ‘*’ is popped and added in postfix. So postfix = “abc*” and stack = {+}. 

Pop '*' and add in postfix

Pop ‘*’ and add in postfix

Now top element is ‘+‘ that also doesn’t have less precedence. Pop it. postfix = “abc*+”. 

Pop '+' and add it in postfix

Pop ‘+’ and add it in postfix

Now stack is empty. So push ‘+’ in the stack. stack = {+}.

Push '+' in the stack

Push ‘+’ in the stack

7th Step: Now i = 6 and exp[i] = ‘d’ i.e., an operand. Add this in the postfix expression. postfix = “abc*+d”.

Add 'd' in the postfix

Add ‘d’ in the postfix

Final Step: Now no element is left. So empty the stack and add it in the postfix expression. postfix = “abc*+d+”.

Pop '+' and add it in postfix

Pop ‘+’ and add it in postfix

Below is the implementation of the above algorithm: 

C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Function to return precedence of operators
int prec(char c) {
    if (c == '^')
        return 3;
    else if (c == '/' || c == '*')
        return 2;
    else if (c == '+' || c == '-')
        return 1;
    else
        return -1;
}

// Function to return associativity of operators
char associativity(char c) {
    if (c == '^')
        return 'R';
    return 'L'; // Default to left-associative
}

// The main function to convert infix expression to postfix expression
void infixToPostfix(char s[]) {
    char result[1000];
    int resultIndex = 0;
    int len = strlen(s);
    char stack[1000];
    int stackIndex = -1;

    for (int i = 0; i < len; i++) {
        char c = s[i];

        // If the scanned character is an operand, add it to the output string.
        if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) {
            result[resultIndex++] = c;
        }
        // If the scanned character is an ‘(‘, push it to the stack.
        else if (c == '(') {
            stack[++stackIndex] = c;
        }
        // If the scanned character is an ‘)’, pop and add to the output string from the stack
        // until an ‘(‘ is encountered.
        else if (c == ')') {
            while (stackIndex >= 0 && stack[stackIndex] != '(') {
                result[resultIndex++] = stack[stackIndex--];
            }
            stackIndex--; // Pop '('
        }
        // If an operator is scanned
        else {
            while (stackIndex >= 0 && (prec(s[i]) < prec(stack[stackIndex]) ||
                                       prec(s[i]) == prec(stack[stackIndex]) &&
                                           associativity(s[i]) == 'L')) {
                result[resultIndex++] = stack[stackIndex--];
            }
            stack[++stackIndex] = c;
        }
    }

    // Pop all the remaining elements from the stack
    while (stackIndex >= 0) {
        result[resultIndex++] = stack[stackIndex--];
    }

    result[resultIndex] = '\0';
    printf("%s\n", result);
}

// Driver code
int main() {
    char exp[] = "a+b*(c^d-e)^(f+g*h)-i";

    // Function call
    infixToPostfix(exp);

    return 0;
}
Java
import java.util.Stack;

public class InfixToPostfix {

    // Function to return precedence of operators
    static int prec(char c) {
        if (c == '^')
            return 3;
        else if (c == '/' || c == '*')
            return 2;
        else if (c == '+' || c == '-')
            return 1;
        else
            return -1;
    }

    // Function to return associativity of operators
    static char associativity(char c) {
        if (c == '^')
            return 'R';
        return 'L'; // Default to left-associative
    }

    // The main function to convert infix expression to postfix expression
    static void infixToPostfix(String s) {
        StringBuilder result = new StringBuilder();
        Stack<Character> stack = new Stack<>();

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);

            // If the scanned character is an operand, add it to the output string.
            if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) {
                result.append(c);
            }
            // If the scanned character is an ‘(‘, push it to the stack.
            else if (c == '(') {
                stack.push(c);
            }
            // If the scanned character is an ‘)’, pop and add to the output string from the stack
            // until an ‘(‘ is encountered.
            else if (c == ')') {
                while (!stack.isEmpty() && stack.peek() != '(') {
                    result.append(stack.pop());
                }
                stack.pop(); // Pop '('
            }
            // If an operator is scanned
            else {
                while (!stack.isEmpty() && (prec(s.charAt(i)) < prec(stack.peek()) ||
                                             prec(s.charAt(i)) == prec(stack.peek()) &&
                                                 associativity(s.charAt(i)) == 'L')) {
                    result.append(stack.pop());
                }
                stack.push(c);
            }
        }

        // Pop all the remaining elements from the stack
        while (!stack.isEmpty()) {
            result.append(stack.pop());
        }

        System.out.println(result);
    }

    // Driver code
    public static void main(String[] args) {
        String exp = "a+b*(c^d-e)^(f+g*h)-i";

        // Function call
        infixToPostfix(exp);
    }
}
Python
def prec(c):
    if c == '^':
        return 3
    elif c == '/' or c == '*':
        return 2
    elif c == '+' or c == '-':
        return 1
    else:
        return -1

def associativity(c):
    if c == '^':
        return 'R'
    return 'L'  # Default to left-associative

def infix_to_postfix(s):
    result = []
    stack = []

    for i in range(len(s)):
        c = s[i]

        # If the scanned character is an operand, add it to the output string.
        if ('a' <= c <= 'z') or ('A' <= c <= 'Z') or ('0' <= c <= '9'):
            result.append(c)
        # If the scanned character is an ‘(‘, push it to the stack.
        elif c == '(':
            stack.append(c)
        # If the scanned character is an ‘)’, pop and add to the output string from the stack
        # until an ‘(‘ is encountered.
        elif c == ')':
            while stack and stack[-1] != '(':
                result.append(stack.pop())
            stack.pop()  # Pop '('
        # If an operator is scanned
        else:
            while stack and (prec(s[i]) < prec(stack[-1]) or
                             (prec(s[i]) == prec(stack[-1]) and associativity(s[i]) == 'L')):
                result.append(stack.pop())
            stack.append(c)

    # Pop all the remaining elements from the stack
    while stack:
        result.append(stack.pop())

    print(''.join(result))

# Driver code
exp = "a+b*(c^d-e)^(f+g*h)-i"

# Function call
infix_to_postfix(exp)
C#
using System;
using System.Collections.Generic;

class Program
{
    // Function to return precedence of operators
    static int Prec(char c)
    {
        if (c == '^')
            return 3;
        else if (c == '/' || c == '*')
            return 2;
        else if (c == '+' || c == '-')
            return 1;
        else
            return -1;
    }

    // Function to return associativity of operators
    static char Associativity(char c)
    {
        if (c == '^')
            return 'R';
        return 'L'; // Default to left-associative
    }

    // The main function to convert infix expression to postfix expression
    static void InfixToPostfix(string s)
    {
        Stack<char> stack = new Stack<char>();
        List<char> result = new List<char>();

        for (int i = 0; i < s.Length; i++)
        {
            char c = s[i];

            // If the scanned character is an operand, add it to the output string.
            if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'))
            {
                result.Add(c);
            }
            // If the scanned character is an ‘(‘, push it to the stack.
            else if (c == '(')
            {
                stack.Push(c);
            }
            // If the scanned character is an ‘)’, pop and add to the output string from the stack
            // until an ‘(‘ is encountered.
            else if (c == ')')
            {
                while (stack.Count > 0 && stack.Peek() != '(')
                {
                    result.Add(stack.Pop());
                }
                stack.Pop(); // Pop '('
            }
            // If an operator is scanned
            else
            {
                while (stack.Count > 0 && (Prec(s[i]) < Prec(stack.Peek()) ||
                                           Prec(s[i]) == Prec(stack.Peek()) &&
                                               Associativity(s[i]) == 'L'))
                {
                    result.Add(stack.Pop());
                }
                stack.Push(c);
            }
        }

        // Pop all the remaining elements from the stack
        while (stack.Count > 0)
        {
            result.Add(stack.Pop());
        }

        Console.WriteLine(string.Join("", result));
    }

    // Driver code
    static void Main()
    {
        string exp = "a+b*(c^d-e)^(f+g*h)-i";

        // Function call
        InfixToPostfix(exp);
    }
}
Javascript
    /* Javascript implementation to convert
    infix expression to postfix*/
    
    //Function to return precedence of operators
    function prec(c) {
        if(c == '^')
            return 3;
        else if(c == '/' || c=='*')
            return 2;
        else if(c == '+' || c == '-')
            return 1;
        else
            return -1;
    }

    // The main function to convert infix expression
    //to postfix expression
    function infixToPostfix(s) {

        let st = []; //For stack operations, we are using JavaScript built in stack
        let result = "";

        for(let i = 0; i < s.length; i++) {
            let c = s[i];

            // If the scanned character is
            // an operand, add it to output string.
            if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'))
                result += c;

            // If the scanned character is an
            // ‘(‘, push it to the stack.
            else if(c == '(')
                st.push('(');

            // If the scanned character is an ‘)’,
            // pop and to output string from the stack
            // until an ‘(‘ is encountered.
            else if(c == ')') {
                while(st[st.length - 1] != '(')
                {
                    result += st[st.length - 1];
                    st.pop();
                }
                st.pop();
            }

            //If an operator is scanned
            else {
                while(st.length != 0 && prec(s[i]) <= prec(st[st.length - 1])) {
                    result += st[st.length - 1];
                    st.pop(); 
                }
                st.push(c);
            }
        }

        // Pop all the remaining elements from the stack
        while(st.length != 0) {
            result += st[st.length - 1];
            st.pop();
        }

        console.log(result + "</br>");
    }
    
    let exp = "a+b*(c^d-e)^(f+g*h)-i";
    infixToPostfix(exp);

// This code is contributed by decode2207.
C++14
#include <bits/stdc++.h>
using namespace std;

// Function to return precedence of operators
int prec(char c) {
    if (c == '^')
        return 3;
    else if (c == '/' || c == '*')
        return 2;
    else if (c == '+' || c == '-')
        return 1;
    else
        return -1;
}

// Function to return associativity of operators
char associativity(char c) {
    if (c == '^')
        return 'R';
    return 'L'; // Default to left-associative
}

// The main function to convert infix expression
// to postfix expression
void infixToPostfix(string s) {
    stack<char> st;
    string result;

    for (int i = 0; i < s.length(); i++) {
        char c = s[i];

        // If the scanned character is
        // an operand, add it to the output string.
        if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'))
            result += c;

        // If the scanned character is an
        // ‘(‘, push it to the stack.
        else if (c == '(')
            st.push('(');

        // If the scanned character is an ‘)’,
        // pop and add to the output string from the stack
        // until an ‘(‘ is encountered.
        else if (c == ')') {
            while (st.top() != '(') {
                result += st.top();
                st.pop();
            }
            st.pop(); // Pop '('
        }

        // If an operator is scanned
        else {
            while (!st.empty() && prec(s[i]) < prec(st.top()) ||
                   !st.empty() && prec(s[i]) == prec(st.top()) &&
                   associativity(s[i]) == 'L') {
                result += st.top();
                st.pop();
            }
            st.push(c);
        }
    }

    // Pop all the remaining elements from the stack
    while (!st.empty()) {
        result += st.top();
        st.pop();
    }

    cout << result << endl;
}

// Driver code
int main() {
    string exp = "a+b*(c^d-e)^(f+g*h)-i";

    // Function call
    infixToPostfix(exp);

    return 0;
}

Output
abcd^e-fgh*+^*+i-

Time Complexity: O(N), where N is the size of the infix expression
Auxiliary Space: O(N), where N is the size of the infix expression

 



Previous Article
Next Article

Similar Reads

Postfix to Infix
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 operat
7 min read
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
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
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
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
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
Practice Tags :