| Home / C & C ++ / |
What is infix, prefix, postfix? How can you convert from one representation to another? How do you evaluate these expressions? |
||||
There are three different ways in which an expression like a+b can be represented. Prefix (Polish) +ab
ab+
a+b
Conversion from infix to postfix Suppose this is the infix expresssion
--------->
As an example
((A + (B - C) * D) ^ E + F)] [(( A ((A + (B - C) * D) ^ E + F)] [((+ A ((A + (B - C) * D) ^ E + F)] [((+(- ABC ((A + (B - C) * D) ^ E + F)] [( ABC-D*+ ((A + (B - C) * D) ^ E + F)] [( ABC-D*+E^F+ ((A + (B - C) * D) ^ E + F)] [ ABC-D*+E^F+
Yes. We need to associate a rank for each symbol of the expression. The rank of an operator is -1 and the rank of an operand is +1. The total rank of an expression can be determined as follows:
Conversion from infix to prefix This is very similar to the method mentioned above, except the fact that we add the special value [ at the start of the expression and ] to the stack and we move through the infix expression from right to left. Also at the end, reverse the output expression got to get the prefix expression.
Evaluation of a postfix expression Here is the pseudocode. As we scan from left to right
If we encounter an operator, pop 2 operand from the stack. The first one popped is called operand2 and the second one is called operand1. Perform Result=operand1 operator operand2. Push the result onto the stack. Repeat the above steps till the end of the input.
This is the same as postfix evaluation, the only difference being that we wont evaluate the expression, but just present the answer. The scanning is done from left to right.
A(B-C)D*+ A((B-C)*D)+ A+((B-C)*D)
Convert from postfix expression to infix The scanning is done from right to left and is similar to what we did above.
Reverse it DCB-*A+ D(B-C)*A+ ((B-C)*D)A+ A+((B-C)*D)
|
||||
