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).

Infix to Prefix Conversion Algorithm

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 untill 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

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(

Input TokenStackExpressionAction
FFAdd F into expression string
^^FPush ‘^’ into stack
)^)FEPush ‘)’ into stack
E^)FEAdd E into expression string
^)-FEPush ‘-‘ into stack
D^)-FEDAdd D into expression string
(^)-FED-‘(‘ Pair matched, so pop operator ‘-‘
FED-^‘-‘ operator has less precedence than ‘^’, so pop ^ and add to expression string
CFED-^CAdd C into expression string
++FED-^C-Pop – because – and + have left associativity
)+)FED-^C-Push ‘)’ into stack
B+)FED-^C-BAdd B into expression string
++)+FED-^C-BPush ‘+’ into stack
A+)+FED-^C-BAAdd A into expression string
(+FED-^C-BA+‘(‘ Pair matched, so pop operator ‘+’
FED-^C-BA++Pop all operators one by one as we have reached end of the expression

Now reverse the expression to get prefix expression ++AB-C^-DEF


Share on