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.
Input: str = “a+b*c-(d/e+f^g^h)”
- 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 it’s precedence value is greater than the precedence value of the character on top, push.
- If it’s precedence value is lower 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:
- Postfix to Infix
- Stack | Set 2 (Infix to Postfix)
- Prefix to Infix Conversion
- Convert Infix To Prefix Notation
- Infix to Prefix conversion using two stacks
- Postfix to Prefix Conversion
- Prefix to Postfix Conversion
- Stack | Set 4 (Evaluation of Postfix Expression)
- Mapping external values to dataframe values in Pandas
- Assign other value to a variable from two possible values
- Find K items with the lowest values
- How to get multiple selected values of select box in php?
- Eigenspace and Eigenspectrum Values in a Matrix
- Maximum and Minimum Values of an Algebraic Expression
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.
Improved By : Rajput-Ji