Convert Infix expression to Postfix expression
Write a program to Convert Infix expression to Postfix.
Infix expression: The expression of the form a operator b (a + b). When an operator is in-between every pair of operands.
Postfix expression: The expression of the form a b operator (ab+). When an operator is followed by every pair of operands.
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 and 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.
Steps to convert Infix expression to Postfix expression using Stack:
- Scan the infix expression from left to right.
- If the scanned character is an operand, output it.
- Else,
- 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.
- ‘^’ operator is right associative and other operators like ‘+’,’-‘,’*’ and ‘/’ are left-associative. Check especially for a condition when both, operator at the top of the stack and the scanned operator 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.)
- If the scanned character is an ‘(‘, push it to the stack.
- If the scanned character is an ‘)’, pop the stack and output it until a ‘(‘ is encountered, and discard both the parenthesis.
- Repeat steps 2-6 until the infix expression is scanned.
- Print the output
- Pop and output from the stack until it is not empty.
Below is the implementation of the above algorithm:
C++14
/* C++ implementation to convert infix expression to postfix*/ #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; } // The main function to convert infix expression // to postfix expression void infixToPostfix(string s) { stack< char > st; // For stack operations, we are using // C++ built in stack string result; for ( int i = 0; i < s.length(); i++) { char 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.top() != '(' ) { result += st.top(); st.pop(); } st.pop(); } // If an operator is scanned else { while (!st.empty() && prec(s[i]) <= prec(st.top())) { 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's code int main() { string exp = "a+b*(c^d-e)^(f+g*h)-i" ; // Function call infixToPostfix( exp ); return 0; } |
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #define MAX_EXPR_SIZE 100 int precedence( char operator) { switch (operator) { case '+' : case '-' : return 1; case '*' : case '/' : return 2; case '^' : return 3; default : return -1; } } int isOperator( char ch) { return (ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '^' ); } char *infixToPostfix( char *infix) { int i, j; int len = strlen (infix); char *postfix = ( char *) malloc ( sizeof ( char ) * (len + 2)); char stack[MAX_EXPR_SIZE]; int top = -1; for (i = 0, j = 0; i < len; i++) { if (infix[i] == ' ' || infix[i] == '\t' ) continue ; if ( isalnum (infix[i])) { postfix[j++] = infix[i]; } else if (infix[i] == '(' ) { stack[++top] = infix[i]; } else if (infix[i] == ')' ) { while (top > -1 && stack[top] != '(' ) postfix[j++] = stack[top--]; if (top > -1 && stack[top] != '(' ) return "Invalid Expression" ; else top--; } else if (isOperator(infix[i])) { while (top > -1 && precedence(stack[top]) >= precedence(infix[i])) postfix[j++] = stack[top--]; stack[++top] = infix[i]; } } while (top > -1) postfix[j++] = stack[top--]; postfix[j] = '\0' ; return postfix; } int main() { char infix[MAX_EXPR_SIZE]; printf ( "Enter an infix expression: " ); gets (infix); char *postfix = infixToPostfix(infix); printf ( "Postfix expression: %s\n" , postfix); free (postfix); return 0; } |
Java
/* Java implementation to convert infix expression to postfix*/ // Note that here we use ArrayDeque class for Stack // operations import java.util.ArrayDeque; import java.util.Deque; import java.util.Stack; class Test { // A utility function to return // precedence of a given operator // Higher returned value means // higher precedence static int Prec( char ch) { switch (ch) { case '+' : case '-' : return 1 ; case '*' : case '/' : return 2 ; case '^' : return 3 ; } return - 1 ; } // The main method that converts // given infix expression // to postfix expression. static String infixToPostfix(String exp) { // initializing empty String for result String result = new String( "" ); // initializing empty stack Deque<Character> stack = new ArrayDeque<Character>(); for ( int i = 0 ; i < exp.length(); ++i) { char c = exp.charAt(i); // If the scanned character is an // operand, add it to output. if (Character.isLetterOrDigit(c)) result += 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 output from the stack // until an '(' is encountered. else if (c == ')' ) { while (!stack.isEmpty() && stack.peek() != '(' ) { result += stack.peek(); stack.pop(); } stack.pop(); } else // an operator is encountered { while (!stack.isEmpty() && Prec(c) <= Prec(stack.peek())) { result += stack.peek(); stack.pop(); } stack.push(c); } } // pop all the operators from the stack while (!stack.isEmpty()) { if (stack.peek() == '(' ) return "Invalid Expression" ; result += stack.peek(); stack.pop(); } return result; } // Driver's code public static void main(String[] args) { String exp = "a+b*(c^d-e)^(f+g*h)-i" ; // Function call System.out.println(infixToPostfix(exp)); } } |
Python
# Python program to convert infix expression to postfix # Class to convert the expression class Conversion: # Constructor to initialize the class variables def __init__( self , capacity): self .top = - 1 self .capacity = capacity # This array is used a stack self .array = [] # Precedence setting self .output = [] self .precedence = { '+' : 1 , '-' : 1 , '*' : 2 , '/' : 2 , '^' : 3 } # check if the stack is empty def isEmpty( self ): return True if self .top = = - 1 else False # Return the value of the top of the stack def peek( self ): return self .array[ - 1 ] # Pop the element from the stack def pop( self ): if not self .isEmpty(): self .top - = 1 return self .array.pop() else : return "$" # Push the element to the stack def push( self , op): self .top + = 1 self .array.append(op) # A utility function to check is the given character # is operand def isOperand( self , ch): return ch.isalpha() # Check if the precedence of operator is strictly # less than top of stack or not def notGreater( self , i): try : a = self .precedence[i] b = self .precedence[ self .peek()] return True if a < = b else False except KeyError: return False # The main function that # converts given infix expression # to postfix expression def infixToPostfix( self , exp): # Iterate over the expression for conversion for i in exp: # If the character is an operand, # add it to output if self .isOperand(i): self .output.append(i) # If the character is an '(', push it to stack elif i = = '(' : self .push(i) # If the scanned character is an ')', pop and # output from the stack until and '(' is found elif i = = ')' : while (( not self .isEmpty()) and self .peek() ! = '(' ): a = self .pop() self .output.append(a) if ( not self .isEmpty() and self .peek() ! = '(' ): return - 1 else : self .pop() # An operator is encountered else : while ( not self .isEmpty() and self .notGreater(i)): self .output.append( self .pop()) self .push(i) # pop all the operator from the stack while not self .isEmpty(): self .output.append( self .pop()) print "".join( self .output) # Driver's code if __name__ = = '__main__' : exp = "a+b*(c^d-e)^(f+g*h)-i" obj = Conversion( len (exp)) # Function call obj.infixToPostfix(exp) # This code is contributed by Nikhil Kumar Singh(nickzuck_007) |
C#
using System; using System.Collections.Generic; /* c# implementation to convert infix expression to postfix*/ // Note that here we use Stack // class for Stack operations public class Test { // A utility function to return // precedence of a given operator // Higher returned value means higher precedence internal static int Prec( char ch) { switch (ch) { case '+' : case '-' : return 1; case '*' : case '/' : return 2; case '^' : return 3; } return -1; } // The main method that converts given infix expression // to postfix expression. public static string infixToPostfix( string exp) { // initializing empty String for result string result = "" ; // initializing empty stack Stack< char > stack = new Stack< char >(); for ( int i = 0; i < exp.Length; ++i) { char c = exp[i]; // If the scanned character is an // operand, add it to output. if ( char .IsLetterOrDigit(c)) { result += 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 output from the stack // until an '(' is encountered. else if (c == ')' ) { while (stack.Count > 0 && stack.Peek() != '(' ) { result += stack.Pop(); } if (stack.Count > 0 && stack.Peek() != '(' ) { return "Invalid Expression" ; // invalid // expression } else { stack.Pop(); } } else // an operator is encountered { while (stack.Count > 0 && Prec(c) <= Prec(stack.Peek())) { result += stack.Pop(); } stack.Push(c); } } // pop all the operators from the stack while (stack.Count > 0) { result += stack.Pop(); } return result; } // Driver's code public static void Main( string [] args) { string exp = "a+b*(c^d-e)^(f+g*h)-i" ; // Function call Console.WriteLine(infixToPostfix(exp)); } } // This code is contributed by Shrikant13 |
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 + "</br>" ); } let exp = "a+b*(c^d-e)^(f+g*h)-i" ; infixToPostfix(exp); // This code is contributed by decode2207. |
abcd^e-fgh*+^*+i-
Time Complexity: O(N), where N is the size of the infix expression
Auxiliary Space: O(N)
Quiz: Stack Questions
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Please Login to comment...