Lets see the precedence of the operators that will be used to
convert the given infix to prefix expression and understand the
logic for conversion.
Precedence
Precedence
| Operator |
Stack precedence |
Input precedence |
| + - |
2 |
1 |
| / * |
4 |
3 |
| ^ |
6 |
7 |
| ( |
0 |
9 |
| ) |
- |
0 |
Logic for conversion
Do refer the code available the end of this section to
understand the following theory.
-
Create two stacks using arrays of type character, one for
operand stack and another one for operator stack.
-
There occurs a situation to perform the following operation:
-
Pop the top of operand stack and save it as operand2.
-
Once again pop the top of operand stack and save it as
operand1.
-
Copy the incoming operator into a temporary expression.
-
Concat the operand1 and then operand2 to this temporary
expression.
-
Finally push this temporary expression to the operand
stack.
- Scan the infix expression from left to right.
-
If the character read is an operand then push it to the
operand stack.
-
Else loop until the operator stack is not empty and stack
precedence of top(of operator stack) is more than the input
precedence.
-
If the input character is ')' then perform step 2
operation until the top of stack is not '('.
-
Pop the top of operator stack because it will obviously be
'(' and break the loop(step 5).
-
Else if the input character is not ')' then perform step 2
operation.
-
If the step 5 condition fails and input character is not ')'
then push the operator into the operator stack.
-
After scanning all the characters of the infix expression,
perform step 2 operation until the operator stack is not
empty.
- Return the top of operand stack.