Infix to Postfix conversion

  Infix to Postfix conversion

================================================================================

  • Infix expression: The expression of the form a operator b (a + b). When an operator is in-between every pair of operands.
  • Postfix expression: The expression of the form a b operator (ab+). When an operator is followed by every pair of operands.
Infix to Postfix conversion



  • Algorithm:
    1. begin
    2. x = read first symbol from infix
    3. if ( x is '(' or ')' )
      1. if (x is '(' )
        1. push (x)
      2. end if
      3. if (x is ')' )
        1. pop() everything from stack and send to output till we get first '(' parenthesis but '(' not send to output
      4. end if
    4. end if
    5. if (x is operator)
      1. if (operator[TOP] < current (x) operator)
        1. push (x) i.e. push current operator on stack
      2. end if
      3. if (operator[TOP] > current (x) operator)
        1. pop(TOP operator) and send to output and push (current x) operator on the stack
      4. end if
      5. if (TOP == -1)
        1. push(x)
      6. end if
    6. end if
    7. x = read next symbol
    8. go to step 3
    9. print output string
    10. end

  • eg.

    • (A + B) * (C - D) / E

    • Solution:

    • Input

      Stack

      Output

      (



       

      A



      A

      +



       

      B



      A B

      )



      A B +

      *



      A B +

      (



      A B +

      C



      A B + C

      -



      A B + C

      D



      A B + C D

      )



      A B + C D -

      /



      A B + C D - *

      E



      A B + C D - * E

       

      A B + C D - * E /

Comments

Popular posts from this blog

TREE

STACK

Evaluation of postfix expression