Write an algorithm for postfix to infix conversion. Consider the following arithmetic expression P: 12, 7, 3, /, ., 2, /, +, 5, *, +, Translate P into infix expression using stack operations.


Q.) Write an algorithm for postfix to infix conversion. Consider the following arithmetic expression P: 12, 7, 3, /, ., 2, /, +, 5, *, +, Translate P into infix expression using stack operations.

Subject: Data Structure and Algorithm

Algorithm for Postfix to Infix Conversion:

  1. Input: A postfix expression P.
  2. Output: An infix expression equivalent to P.
  3. Stack: Create an empty stack.
  4. For each token T in P:
    • If T is an operand (e.g., a digit):
      • Push T onto the stack.
    • If T is an operator:
      • Pop the top two operands from the stack (say, A and B).
      • Concatenate A, T, and B (i.e., A o B, where o is the operator).
      • Push the resulting expression onto the stack.
  5. Repeat step 4 for all tokens in P.
  6. The top of the stack now contains the infix expression equivalent to P.

Example:

Given the postfix expression P: 12, 7, 3, /, ., 2, /, +, 5, *, +, we can translate it into an infix expression using the following steps:

  1. Push 12 onto the stack.
  2. Push 7 onto the stack.
  3. Push 3 onto the stack.
  4. Pop the top two operands from the stack (7 and 3) and concatenate them with the division operator (/) to form 7/3.
  5. Push 7/3 onto the stack.
  6. Push . onto the stack.
  7. Push 2 onto the stack.
  8. Pop the top two operands from the stack (2 and .) and concatenate them with the multiplication operator (*) to form 2..
  9. Push 2* onto the stack.
  10. Pop the top two operands from the stack (7/3 and 2*) and concatenate them with the addition operator (+) to form (7/3) + (2*).
  11. Push (7/3) + (2*) onto the stack.
  12. Push 5 onto the stack.
  13. Pop the top two operands from the stack ((7/3) + (2*)) and 5) and concatenate them with the multiplication operator () to form ((7/3) + (2)) * 5.
  14. Push ((7/3) + (2*)) * 5 onto the stack.
  15. Pop the top two operands from the stack (((7/3) + (2*)) * 5) and +) to form (((7/3) + (2*)) * 5) + .
  16. The top of the stack now contains the infix expression equivalent to P: ((7/3) + (2*)) * 5 + .

Final Answer:

(((7/3) + (2*)) * 5) +