Convert Infix To Prefix Notation
Given an infix expression, the task is to convert it to a prefix expression.
Infix Expression: The expression of type a ‘operator’ b (a+b, where + is an operator) i.e., when the operator is between two operands.
Prefix Expression: The expression of type ‘operator’ a b (+ab where + is an operator) i.e., when the operator is placed before the operands.
Input: A * B + C / D
Output: + * A B/ C D
Input: (A – B/C) * (A/K-L)
How to convert infix expression to prefix expression?
To convert an infix expression to a prefix expression, we can use the stack data structure. The idea is as follows:
- Step 1: Reverse the infix expression. Note while reversing each ‘(‘ will become ‘)’ and each ‘)’ becomes ‘(‘.
- Step 2: Convert the reversed infix expression to “nearly” postfix expression.
- While converting to postfix expression, instead of using pop operation to pop operators with greater than or equal precedence, here we will only pop the operators from stack that have greater precedence.
- Step 3: Reverse the postfix expression.
The stack is used to convert infix expression to postfix form.
See the below image for a clear idea:
Below is the C++ implementation of the algorithm.
- Time Complexity: O(n)
- 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
- Auxiliary Space: O(n) because we are keeping a stack.
My Personal Notes arrow_drop_up
Please Login to comment...