Infix Post Pre
Infix Post Pre
using stack
Below are the steps to implement the above idea:
1. Scan the infix expression from left to right.
1. If the scanned character is an operand, put it in the postfix expression.
1. Otherwise, do the following
If the precedence and associativity of the scanned operator are greater
than the precedence and associativity of the operator in the stack [or
the stack is empty or the stack contains a ‘(‘ ], then push it in the stack.
[‘^‘ operator is right associative and other operators like ‘+‘,’–‘,’*‘ and ‘/‘
are left-associative].
o Check especially for a condition when the operator at the top
of the stack and the scanned operator both are ‘^‘. In this
condition, the precedence of the scanned operator is higher
due to its right associativity. So it will be pushed into the
operator stack.
o In all the other cases when the top of the operator stack is the
same as the scanned operator, then pop the operator from
the stack because of left associativity due to which the
scanned operator has less precedence.
Else, Pop all the operators from the stack which are greater than or
equal to in precedence than that of the scanned operator.
o After doing that Push the scanned operator to the stack. (If
you encounter parenthesis while popping then stop there and
push the scanned operator in the stack.)
1. If the scanned character is a ‘(‘, push it to the stack.
1. If the scanned character is a ‘)’, pop the stack and output it until a ‘(‘ is
encountered, and discard both the parenthesis.
1. Repeat steps 2-5 until the infix expression is scanned.
1. Once the scanning is over, Pop the stack and add the operators in the
postfix expression until it is not empty.
1. Finally, print the postfix expression.
To convert an infix expression (e.g., A + B * C) to a postfix expression (e.g., A B C * +) using
a stack, you can follow these rules:
If the character is an operand (e.g., a variable or number), directly append it to the postfix list.
After reading the entire infix expression, pop any remaining operators from the stack and
append them to the postfix list.
1. x+y*z/w+u
2. a+b*(c^d-e)^(f+g*h)-i
Detailed Rules
1. Reverse the infix expression
Once you've generated the postfix expression from the reversed input, reverse it to get the final
prefix expression.
1. x+y*z/w+u
2. a+b*(c^d-e)^(f+g*h)-i
Steps:
Example: For the prefix expression + 9 * 2 6, the evaluation steps would be:
Steps:
Example: For the postfix expression 9 2 6 * +, the evaluation steps would be: