Prefix notation is a notation for writing arithmetic expressions in which the operands appear after their operators. There are no precedence rules to learn.
Let’s assume the below
- Operands are real numbers in real digits. (Later we will Enhance the solution for any number)
- Permitted operators: +,-, *, /, ^(exponentiation)
- Blanks are NOT permitted in expression.
- Parenthesis are permitted
Postfix: +54 Output: 9 Explanation: Infix expression of the above prefix is: 5+ 4 which resolves to 9 Postfix: -/*2*5+3652 Output: 16 Explanation: Infix expression of above prefix is: 2 * (5 *(3+6))/5-2 which resolves to 16
Approach: Use Stack
Reverse the given expression and Iterate through it, one character at a time
- If the character is an operand, push it to the operand stack.
- If the character is an operator,
- pop the operand from the stack, say it’s s1.
- pop another operand from the stack, say it’s s2.
- perform (s1 operator s2) and push it to stack.
- Once the expression iteration is completed, The stack will have the final result. pop from the stack and return the result.
Please see the walkthrough of an example below for more understanding.
Prefix Expression: -/*2*5+3652 Evaluation: 16.0