Data Structures and Algorithms - Old Questions

3. Explain In-fix to Postfix Conversion Algorithm. Illustrate it with an example. What changes should be made for converting postfix to prefix.

10 marks | Asked in 2068

Algorithm to convert infix to postfix expression

1. Scan the infix string from left to right.

2. Initialize an empty stack.

3. If the scanned character is an operand, add it to postfix sting

4. If the scanned character is an operator, PUSH the character to stack.

5. If the top operator in stack has equal or higher precedence than scanned operator then POP the operator present in stack and add it to postfix string else PUSH the scanned character to stack.

6. If the scanned character is a left parenthesis ‘(‘, PUSH it to stack.

7. If the scanned character is a right parenthesis ‘)’, POP and add to postfix string from stack until an ‘(‘ is encountered. Ignore both '(' and ')'.

8. Repeat step 3-7 till all the characters are scanned.

9. After all character are scanned POP the characters and add to postfix string from the stack until it is not empty.

Example:

Infix expression: A*B+C

characters

stacks

Postfix expression

A

 

A

*

*

A

B

*

AB

+

+

AB*

C

+

AB*C

 

 

AB*C+






Postfix expression: AB*C+


Now,

To convert postfix to prefix we use following algorithm:

1. Read the Postfix expression from left to right

2. If the symbol is an operand, then push it onto the Stack

3. If the symbol is an operator, then pop two operands from the Stack 

Create a string by concatenating the two operands and the operator before them. 

    string = operator + operand2 + operand1 

        And push the resultant string back to Stack

4. Repeat the above steps until end of Prefix expression.