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*+
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*+-Input: a+b*c
Output: abc*+
Approach:
- If the input character is an operand, print it.
- 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.
- If the input character is ‘)’, then pop and print until top is ‘(‘. (Pop ‘(‘ but don’t print it.)
- If stack becomes empty before encountering ‘(‘, then it’s a invalid expression.
- Repeat steps 1-4 until input expression is completely read.
- 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 |
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:
- If the input character is an operand, print it.
- 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.
- If the input character is ‘)’, then pop and print until top is ‘(‘. (Pop ‘(‘ but don’t print it.)
- If stack becomes empty before encountering ‘(‘, then it’s a invalid expression.
- Repeat steps 1-4 until input expression is completely read.
- Pop the remaining elements from stack and print them.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Postfix to Infix
- Stack | Set 2 (Infix to Postfix)
- Infix to Prefix conversion using two stacks
- Convert Infix To Prefix Notation
- Program to convert Infix notation to Expression Tree
- Prefix to Infix Conversion
- Stack | Set 4 (Evaluation of Postfix Expression)
- Postfix to Prefix Conversion
- Prefix to Postfix Conversion
- Mapping external values to dataframe values in Pandas
- Python | Creating tensors using different functions in Tensorflow
- Color N boxes using M colors such that K boxes have different color from the box on its left
- Python | Plotting Different types of style charts in excel sheet using XlsxWriter module
- Queries for elements having values within the range A to B in the given index range using Segment Tree
- How to Find Duplicate Values in a SQL Table using Python?
- Code valid in both C and C++ but produce different output
- Different Python IDEs and Code Editors
- Maximum and Minimum Values of an Algebraic Expression
- Count the number of words having sum of ASCII values less than and greater than k
- Eigenspace and Eigenspectrum Values in a Matrix
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

