Convert Infix expression to Postfix expression

Last Updated : 26 Dec, 2023

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”.

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

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

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

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

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

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

Pop ‘+’ and add it in postfix

Now stack is empty. So push ‘+’ in the stack. 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”.

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

Below is the implementation of the above algorithm:Â

C++14

 #include 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 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; }

C

 #include #include #include   // 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 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);     } }

Python3

 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 stack = new Stack();         List result = new List();           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();         }           document.write(result + "
");     }           let exp = "a+b*(c^d-e)^(f+g*h)-i";     infixToPostfix(exp);   // This code is contributed by decode2207.

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
Next