While we use infix expressions in our day to day lives. Computers have trouble understanding this format because they need to keep in mind rules of operator precedence and also brackets. Prefix and Postfix expressions are easier for a computer to understand and evaluate.
Given two operands and and an operator , the infix notation implies that O will be placed in between a and b i.e . When the operator is placed after both operands i.e , it is called postfix notation. And when the operator is placed before the operands i.e , the expression in prefix notation.
Given any infix expression we can obtain the equivalent prefix and postfix format.
Input : A * B + C / D Output : + * A B/ C D Input : (A - B/C) * (A/K-L) Output : *-A/BC-/AKL
To convert an infix to postfix expression refer to this article Stack | Set 2 (Infix to Postfix). We use the same to convert Infix to Prefix.
- Step 1: Reverse the infix expression i.e A+B*C will become C*B+A. Note while reversing each ‘(‘ will become ‘)’ and each ‘)’ becomes ‘(‘.
- Step 2: Obtain the postfix expression of the modified expression i.e CB*A+.
- Step 3: Reverse the postfix expression. Hence in our example prefix is +A*BC.
Below is the C++ implementation of the algorithm.
Stack operations like push() and pop() are performed in constant time. Since we scan all the characters in the expression once the complexity is linear in time i.e .
- Prefix to Infix Conversion
- Infix to Prefix conversion using two stacks
- Postfix to Infix
- Stack | Set 2 (Infix to Postfix)
- Print all words matching a pattern in CamelCase Notation Dictonary
- Infix to Postfix using different Precedence Values for In-Stack and Out-Stack
- Longest prefix which is also suffix
- Postfix to Prefix Conversion
- Prefix to Postfix Conversion
- Evaluation of Prefix Expressions
- String from prefix and suffix of given two strings
- Maximum occurrence of prefix in the Array
- Strings from an array which are not prefix of any other string
- Longest Common Prefix Matching | Set-6
- Longest Common Prefix using Trie
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.