Infix to Prefix conversion

 Infix to Prefix conversion

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

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

  • Algorithm:
    1. begin
    2. first reverse the infix expression
    3. replace the parenthesis as every "(" as ")" and every ")" as "("
    4. convert the modified expression to postfix by using infix to postfix algorithm
    5. reverse the final postfix string to get the resulted prefix expression

  • eg.

    • (A + B ^ C) * D + E ^ S

    • Solution:

      • S ^ E + D * ) C ^ B + A (
      • S ^ E + D * ( C ^ B + A )
      • Input

        Stack

        Output

        S



        S

        ^



        S

        E



        S E

        +



        S E ^

        D



        S E ^ D

        *



        S E ^ D

        (



        S E ^ D

        C



        S E ^ D C

        ^



        S E ^ D C

        B



        S E ^ D C B

        +



        S E ^ D C B ^

        A



        S E ^ D C B ^ A

        )



        S E ^ D C B ^ A +

         



        S E ^ D C B ^ A + * +


      • result = S E ^ D C B ^ A + * +
      • reverse above expression to get final output
        • + * + A ^ B C D ^ E S


Comments

Popular posts from this blog

TREE

STACK

Evaluation of postfix expression