Lets see the precedence of the operators that will be used to
convert the given infix to postfix 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 an operator stack using arrays of type character.
- Scan the infix expression from left to right.
-
If the character read is an operand then add it to the postfix
expression.
-
Else loop until the stack is not empty and stack precedence of
top is more than the input precedence.
-
If the input character is ')' then pop the top of the
stack and add it to the postfix expression until the top
of stack is not '('.
-
Once again pop the top of stack because it will obviously
be '(' and break the loop(step 4).
-
Else if the input character is not ')' then pop the top of
stack and add to it the postfix expression.
-
If the step 4 condition fails and input character is not ')'
then push the operator into the stack.
-
After scanning all the characters of the infix expression, pop
the top of operand stack and add it to the postfix expression
untill the stack is not empty.
- Return the postfix expression.