Open In App

Infix to Postfix using different Precedence Values for In-Stack and Out-Stack

Last Updated : 19 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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 precedence functions. 
Infix expression example: a+b*c 
Its corresponding postfix expression: abc*+

Following steps explains how these conversion has done.

Step 1: a + bc* (Here we have two operators: + and * in which * has higher precedence and hence it will be evaluated first).

Step 2: abc*+ (Now we have one operator left which is + so it is evaluated)

  
To know more about infix and postfix expressions visit the links. 
Note : In this article, we are assuming that all operators are left to right associative.
Examples:

Input: str = “a+b*c-(d/e+f*g*h)” 
Output: abc*+de/fg*h*+-

Step 1: a+b*c-(de/+f*g*h)

Step 2: a+b*c-(de/+fg* *h)

Step 3: a+b*c-(de/+fg*h*)

Step 4: a+b*c-(de/fg*h*+)

Step 5: a+bc*-de/fg*h*+

Step 6: abc*+-de/fg*h*+

Step 7: abc*+de/fg*h*+-

Input: a+b*c/h 
Output: abc*h/+

Step 1: a+bc*/h

Step 2: a+bc*h/

Step 3: abc*h/+

Approach:

  1. If the input character is an operand, print it.
  2. If the input character is an operator- 
    • If stack is empty push it to the stack.
    • If its precedence value is greater than the precedence value of the character on top, push.
    • If its precedence value is lower or equal then pop from stack and print while precedence of top char is more than the precedence value of the input character.
  3. If the input character is ‘)’, then pop and print until top is ‘(‘. (Pop ‘(‘ but don’t print it.)
  4. If stack becomes empty before encountering ‘(‘, then it’s a invalid expression.
  5. Repeat steps 1-4 until input expression is completely read.
  6. Pop the remaining elements from stack and print them.

The above method handles right associativity of exponentiation operator (here, ^) by assigning it higher precedence value outside stack and lower precedence value inside stack whereas it’s opposite for left associative operators.
Below is the implementation of the above approach:

C++




// C++ program to convert an infix expression to a
// postfix expression using two precedence function
#include <bits/stdc++.h>
using namespace std;
 
// to check if the input character
// is an operator or a '('
int isOperator(char input)
{
    switch (input) {
    case '+':
        return 1;
    case '-':
        return 1;
    case '*':
        return 1;
    case '%':
        return 1;
    case '/':
        return 1;
    case '(':
        return 1;
    }
    return 0;
}
 
// to check if the input character is an operand
int isOperand(char input)
{
    if (input >= 65 && input <= 90
        || input >= 97 && input <= 122)
        return 1;
    return 0;
}
 
// function to return precedence value
// if operator is present in stack
int inPrec(char input)
{
    switch (input) {
    case '+':
    case '-':
        return 2;
    case '*':
    case '%':
    case '/':
        return 4;
    case '(':
        return 0;
    }
}
 
// function to return precedence value
// if operator is present outside stack.
int outPrec(char input)
{
    switch (input) {
    case '+':
    case '-':
        return 1;
    case '*':
    case '%':
    case '/':
        return 3;
    case '(':
        return 100;
    }
}
 
// function to convert infix to postfix
void inToPost(char* input)
{
    stack<char> s;
 
    // while input is not NULL iterate
    int i = 0;
    while (input[i] != '\0') {
 
        // if character an operand
        if (isOperand(input[i])) {
            printf("%c", input[i]);
        }
 
        // if input is an operator, push
        else if (isOperator(input[i])) {
            if (s.empty()
                || outPrec(input[i]) > inPrec(s.top()))
                s.push(input[i]);
            else {
                while (!s.empty()
                    && outPrec(input[i]) < inPrec(s.top())) {
                    printf("%c", s.top());
                    s.pop();
                }
                s.push(input[i]);
            }
        }
 
        // condition for opening bracket
        else if (input[i] == ')') {
            while (s.top() != '(') {
                printf("%c", s.top());
                s.pop();
 
                // if opening bracket not present
                if (s.empty()) {
                    printf("Wrong input\n");
                    exit(1);
                }
            }
 
            // pop the opening bracket.
            s.pop();
        }
        i++;
    }
 
    // pop the remaining operators
    while (!s.empty()) {
        if (s.top() == '(') {
            printf("\n Wrong input\n");
            exit(1);
        }
        printf("%c", s.top());
        s.pop();
    }
}
 
// Driver code
int main()
{
    char input[] = "a+b*c-(d/e+f*g*h)";
    inToPost(input);
    return 0;
}


Java




import static java.lang.System.exit;
import java.util.Stack;
 
// Java program to convert an infix expression to a
// postfix expression using two precedence function
class GFG {
 
    // to check if the input character
    // is an operator or a '('
    static int isOperator(char input)
    {
        switch (input) {
        case '+':
            return 1;
        case '-':
            return 1;
        case '*':
            return 1;
        case '%':
            return 1;
        case '/':
            return 1;
        case '(':
            return 1;
        }
        return 0;
    }
 
    // to check if the input character is an operand
    static int isOperand(char input)
    {
        if (input >= 65 && input <= 90
            || input >= 97 && input <= 122) {
            return 1;
        }
        return 0;
    }
 
    // function to return precedence value
    // if operator is present in stack
    static int inPrec(char input)
    {
        switch (input) {
        case '+':
        case '-':
            return 2;
        case '*':
        case '%':
        case '/':
            return 4;
        case '(':
            return 0;
        }
        return 0;
    }
 
    // function to return precedence value
    // if operator is present outside stack.
    static int outPrec(char input)
    {
        switch (input) {
        case '+':
        case '-':
            return 1;
        case '*':
        case '%':
        case '/':
            return 3;
        case '(':
            return 100;
        }
        return 0;
    }
 
    // function to convert infix to postfix
    static void inToPost(char[] input)
    {
        Stack<Character> s = new Stack<Character>();
 
        // while input is not NULL iterate
        int i = 0;
        while (input.length != i) {
 
            // if character an operand
            if (isOperand(input[i]) == 1) {
                System.out.printf("%c", input[i]);
            } // if input is an operator, push
            else if (isOperator(input[i]) == 1) {
                if (s.empty()
                    || outPrec(input[i]) > inPrec(s.peek())) {
                    s.push(input[i]);
                }
                else {
                    while (!s.empty()
                           && outPrec(input[i]) < inPrec(s.peek())) {
                        System.out.printf("%c", s.peek());
                        s.pop();
                    }
                    s.push(input[i]);
                }
            } // condition for opening bracket
            else if (input[i] == ')') {
                while (s.peek() != '(') {
                    System.out.printf("%c", s.peek());
                    s.pop();
 
                    // if opening bracket not present
                    if (s.empty()) {
                        System.out.printf("Wrong input\n");
                        exit(1);
                    }
                }
 
                // pop the opening bracket.
                s.pop();
            }
            i++;
        }
 
        // pop the remaining operators
        while (!s.empty()) {
            if (s.peek() == '(') {
                System.out.printf("\n Wrong input\n");
                exit(1);
            }
            System.out.printf("%c", s.peek());
            s.pop();
        }
    }
 
    // Driver code
    static public void main(String[] args)
    {
        char input[] = "a+b*c-(d/e+f*g*h)".toCharArray();
        inToPost(input);
    }
}
 
// This code is contributed by Rajput-Ji


Python3




# Python3 program to convert an infix
# expression to a postfix expression
# using two precedence function
 
# To check if the input character
# is an operator or a '('
def isOperator(input):
     
    switch = {
        '+': 1,
        '-': 1,
        '*': 1,
        '/': 1,
        '%': 1,
        '(': 1,
    }
     
    return switch.get(input, False)
 
# To check if the input character is an operand
def isOperand(input):
     
    if ((ord(input) >= 65 and ord(input) <= 90) or
        (ord(input) >= 97 and ord(input) <= 122)):
        return 1
         
    return 0
 
# Function to return precedence value
# if operator is present in stack
def inPrec(input):
     
    switch = {
        '+': 2,
        '-': 2,
        '*': 4,
        '/': 4,
        '%': 4,
        '(': 0,
    }
     
    return switch.get(input, 0)
 
# Function to return precedence value
# if operator is present outside stack.
def outPrec(input):
     
    switch = {
        '+': 1,
        '-': 1,
        '*': 3,
        '/': 3,
        '%': 3,
        '(': 100,
    }
     
    return switch.get(input, 0)
 
# Function to convert infix to postfix
def inToPost(input):
     
    i = 0
    s = []
 
    # While input is not NULL iterate
    while (len(input) != i):
 
        # If character an operand
        if (isOperand(input[i]) == 1):
            print(input[i], end = "")
 
        # If input is an operator, push
        elif (isOperator(input[i]) == 1):
            if (len(s) == 0 or
                outPrec(input[i]) >
                 inPrec(s[-1])):
                s.append(input[i])
             
            else:
                while(len(s) > 0 and
                      outPrec(input[i]) <
                      inPrec(s[-1])):
                    print(s[-1], end = "")
                    s.pop()
                     
                s.append(input[i])
 
        # Condition for opening bracket
        elif(input[i] == ')'):
            while(s[-1] != '('):
                print(s[-1], end = "")
                s.pop()
 
                # If opening bracket not present
                if(len(s) == 0):
                    print('Wrong input')
                    exit(1)
 
            # pop the opening bracket.
            s.pop()
             
        i += 1
         
    # pop the remaining operators
    while(len(s) > 0):
        if(s[-1] == '('):
            print('Wrong input')
            exit(1)
             
        print(s[-1], end = "")
        s.pop()
 
# Driver code
input = "a+b*c-(d/e+f*g*h)"
 
inToPost(input)
 
# This code is contributed by dheeraj_2801


C#




// C# program to convert an infix expression to a
// postfix expression using two precedence function
using System.Collections.Generic;
using System;
public class GFG {
 
    // to check if the input character
    // is an operator or a '('
    static int isOperator(char input)
    {
        switch (input) {
        case '+':
            return 1;
        case '-':
            return 1;
        case '*':
            return 1;
        case '%':
            return 1;
        case '/':
            return 1;
        case '(':
            return 1;
        }
        return 0;
    }
 
    // to check if the input character is an operand
    static int isOperand(char input)
    {
        if (input >= 65 && input <= 90
            || input >= 97 && input <= 122) {
            return 1;
        }
        return 0;
    }
 
    // function to return precedence value
    // if operator is present in stack
    static int inPrec(char input)
    {
        switch (input) {
        case '+':
        case '-':
            return 2;
        case '*':
        case '%':
        case '/':
            return 4;
        case '(':
            return 0;
        }
        return 0;
    }
 
    // function to return precedence value
    // if operator is present outside stack.
    static int outPrec(char input)
    {
        switch (input) {
        case '+':
        case '-':
            return 1;
        case '*':
        case '%':
        case '/':
            return 3;
        case '(':
            return 100;
        }
        return 0;
    }
 
    // function to convert infix to postfix
    static void inToPost(char[] input)
    {
        Stack<char> s = new Stack<char>();
 
        // while input is not NULL iterate
        int i = 0;
        while (input.Length != i) {
 
            // if character an operand
            if (isOperand(input[i]) == 1) {
                Console.Write(input[i]);
            }
 
            // if input is an operator, push
            else if (isOperator(input[i]) == 1) {
                if (s.Count == 0
                    || outPrec(input[i]) > inPrec(s.Peek())) {
                    s.Push(input[i]);
                }
                else {
                    while (s.Count != 0
                           && outPrec(input[i]) < inPrec(s.Peek())) {
                        Console.Write(s.Peek());
                        s.Pop();
                    }
                    s.Push(input[i]);
                }
            } // condition for opening bracket
            else if (input[i] == ')') {
                while (s.Peek() != '(') {
                    Console.Write(s.Peek());
                    s.Pop();
 
                    // if opening bracket not present
                    if (s.Count == 0) {
                        Console.Write("Wrong input\n");
                        return;
                    }
                }
 
                // pop the opening bracket.
                s.Pop();
            }
            i++;
        }
 
        // pop the remaining operators
        while (s.Count != 0) {
            if (s.Peek() == '(') {
                Console.Write("\n Wrong input\n");
                return;
            }
            Console.Write(s.Peek());
            s.Pop();
        }
    }
 
    // Driver code
    static public void Main()
    {
        char[] input = "a+b*c-(d/e+f*g*h)".ToCharArray();
        inToPost(input);
    }
}
 
// This code is contributed by Rajput-Ji


Javascript




<script>
    // Javascript program to convert an infix expression to a
    // postfix expression using two precedence function
     
    // to check if the input character
    // is an operator or a '('
    function isOperator(input)
    {
        switch (input) {
          case '+':
              return 1;
          case '-':
              return 1;
          case '*':
              return 1;
          case '%':
              return 1;
          case '/':
              return 1;
          case '(':
              return 1;
        }
        return 0;
    }
   
    // to check if the input character is an operand
    function isOperand(input)
    {
        if (input.charCodeAt() >= 65 && input.charCodeAt() <= 90
            || input.charCodeAt() >= 97 && input.charCodeAt() <= 122) {
            return 1;
        }
        return 0;
    }
   
    // function to return precedence value
    // if operator is present in stack
    function inPrec(input)
    {
        switch (input) {
          case '+':
          case '-':
              return 2;
          case '*':
          case '%':
          case '/':
              return 4;
          case '(':
              return 0;
        }
        return 0;
    }
   
    // function to return precedence value
    // if operator is present outside stack.
    function outPrec(input)
    {
        switch (input) {
          case '+':
          case '-':
              return 1;
          case '*':
          case '%':
          case '/':
              return 3;
          case '(':
              return 100;
        }
        return 0;
    }
   
    // function to convert infix to postfix
    function inToPost(input)
    {
        let s = [];
   
        // while input is not NULL iterate
        let i = 0;
        while (input.length != i) {
   
            // if character an operand
            if (isOperand(input[i]) == 1) {
                document.write(input[i]);
            }
   
            // if input is an operator, push
            else if (isOperator(input[i]) == 1) {
                if (s.length == 0
                    || outPrec(input[i]) > inPrec(s[s.length - 1])) {
                    s.push(input[i]);
                }
                else {
                    while (s.length != 0
                           && outPrec(input[i]) < inPrec(s[s.length - 1])) {
                        document.write(s[s.length - 1]);
                        s.pop();
                    }
                    s.push(input[i]);
                }
            } // condition for opening bracket
            else if (input[i] == ')') {
                while (s[s.length - 1] != '(') {
                    document.write(s[s.length - 1]);
                    s.pop();
   
                    // if opening bracket not present
                    if (s.length == 0) {
                        document.write("Wrong input" + "</br>");
                        return;
                    }
                }
   
                // pop the opening bracket.
                s.pop();
            }
            i++;
        }
   
        // pop the remaining operators
        while (s.length != 0) {
            if (s[s.length - 1] == '(') {
                document.write("</br>" + " Wrong input" + "</br>");
                return;
            }
            document.write(s[s.length - 1]);
            s.pop();
        }
    }
     
    let input = "a+b*c-(d/e+f*g*h)".split('');
      inToPost(input);
     
    // This code is contributed by rameshtravel07.
</script>


Output: 

abc*+de/fg*h*+-

 

How to handle operators with right to left associativity? 
For example, power operator ^. The postfix of “a^b^c” would be “abc^^”, but the above solution would print postfix as “ab^c^” which is wrong. 
In the above implementation, when we see an operator with equal precedence, we treat it same as lower. We need to consider the same if the two operators have left to associativity. But in case of right to left associativity, we need to treat it as higher precedence and push it to the stack.
Approach:

  1. If the input character is an operand, print it.
  2. If the input character is an operator- 
    • If stack is empty push it to the stack.
    • If ((its precedence value is greater than the precedence value of the character on top) OR (precedence is same AND associativity is right to left)), push.
    • If ((its precedence value is lower) OR (precedence is same AND associativity is left to right)), then pop from stack and print while precedence of top char is more than the precedence value of the input character.
  3. If the input character is ‘)’, then pop and print until top is ‘(‘. (Pop ‘(‘ but don’t print it.)
  4. If stack becomes empty before encountering ‘(‘, then it’s a invalid expression.
  5. Repeat steps 1-4 until input expression is completely read.
  6. Pop the remaining elements from stack and print them.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads