Infix to Prefix conversion Algorithm with example
To convert Infix to prefix using the stack, first reverse the infix expression and at last again
reverse the output expression to get prefix expression. We have operator’s stack, output’s
stack and one input string. Operator’s stack works as FILO (First In Last Out). Output’s stack
works as FIFO (First In First Out).
Iterate the given expression from left to right, one character at a time
Step 1: First reverse the given expression
Step 2: If the scanned character is an operand, put it into prefix expression.
Step 3: If the scanned character is an operator and operator's stack is empty, push operator
into operators' stack.
Step 4: If the operator's stack is not empty, there may be following possibilities.
If the precedence of scanned operator is greater than the top most operator of operator's
stack, push this operator into operator 's stack.
If the precedence of scanned operator is less than the top most operator of operator's stack,
pop the operators from operator's stack until we find a low precedence operator than the
scanned character.
If the precedence of scanned operator is equal then check the associativity of the operator.
If associativity left to right then simply put into stack. If associativity right to left then pop the
operators from stack until we find a low precedence operator.
If the scanned character is opening round bracket ( '(' ), push it into operator's stack.
If the scanned character is closing round bracket ( ')' ), pop out operators from operator's
stack until we find an opening bracket ('(' ).
Repeat Step 2,3 and 4 till expression has character
Step 5: Now pop out all the remaining operators from the operator's stack and push into
postfix expression.
Step 6: Exit
Now reverse the expression to get prefix expression
Input
Stack Expression Action
Token
F F Add F into expression string
^ ^ F Push ‘^’ into stack
) ^) FE Push ‘)’ into stack
E ^) FE Add E into expression string
– ^)- FE Push ‘-‘ into stack
D ^)- FED Add D into expression string
( ^)- FED- ‘(‘ Pair matched, so pop operator ‘-‘
‘-‘ operator has less precedence than ‘^’, so pop ^ and add
– – FED-^
to expression string
C – FED-^C Add C into expression string
+ + FED-^C- Pop – because – and + have left associativity
) +) FED-^C- Push ‘)’ into stack
B +) FED-^C-B Add B into expression string
+ +)+ FED-^C-B Push ‘+’ into stack
A +)+ FED-^C-BA Add A into expression string
( + FED-^C-BA+ ‘(‘ Pair matched, so pop operator ‘+’
FED-^C- Pop all operators one by one as we have reached end of the
BA++ expression
Infix to Prefix conversion example
Infix Expression: (A+B)+C-(D-E)^F
First reverse the given infix expression
After Reversing: F^)E-D(-C+)B+A(
Example : Evaluation of Prefix expression