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 Q.
  3. Stack S: Initialize an empty stack S.
  4. for i = 1 to n:
    • Read the ith character x from P.
    • if x is an operand:
      • Push x onto S.
    • else if x is an operator:
      • Pop the top two operands, say a and b, from S.
      • Push the infix expression "(a x b)" onto S.
  5. Pop the top element from S. This is the infix expression Q.
  6. Return Q.

Example:

Given the postfix expression P: 12, 7, 3, /, ., 2, /, +, 5, *, +, we can translate it into the infix expression Q using the algorithm above:

  1. Initialize the stack S: S = {}
  2. Read the first character from P: x = 1
    • Since x is an operand, push it onto S: S = {1}
  3. Read the second character from P: x = 2
    • Since x is an operand, push it onto S: S = {1, 2}
  4. Read the third character from P: x = 7
    • Since x is an operand, push it onto S: S = {1, 2, 7}
  5. Read the fourth character from P: x = /
    • Since x is an operator, pop the top two operands, a and b, from S: a = 7, b = 2
    • Push the infix expression "(a x b)" onto S: S = {1, "(7 / 2)"}
  6. Read the fifth character from P: x = .
    • Since x is an operator, pop the top two operands, a and b, from S: a = "(7 / 2)", b = 1
    • Push the infix expression "(a x b)" onto S: S = {"(12 / 2)"}
  7. Read the sixth character from P: x = 3
    • Since x is an operand, push it onto S: S = {"(12 / 2)", 3}
  8. Read the seventh character from P: x = /
    • Since x is an operator, pop the top two operands, a and b, from S: a = 3, b = "(12 / 2)"
    • Push the infix expression "(a x b)" onto S: S = { "((12 / 2) / 3)"}
  9. Read the eighth character from P: x = +
    • Since x is an operator, pop the top two operands, a and b, from S: a = "((12 / 2) / 3)", b = 5
    • Push the infix expression "(a x b)" onto S: S = { "(12 / 2) / 3 + 5)"}
  10. Read the ninth character from P: x = *
    • Since x is an operator, pop the top two operands, a and b, from S: a = 5, b = "(12 / 2) / 3 + 5)"
    • Push the infix expression "(a x b)" onto S: S = { "(12 / 2) / 3 + 5) * 2)"}
  11. Read the tenth character from P: x = +
    • Since x is an operator, pop the top two operands, a and b, from S: a = ") / 3 + 5) * 2)", b = ") / 3 + 5)"
    • Push the infix expression "(a x b)" onto S: S = { "(12 / 2) + (12 / 2) / 3 + 5) * 2)"}
  12. Pop the top element from S: Q = "(12 / 2) + (12 / 2) / 3 + 5) * 2)"

Therefore, the infix expression Q is: (12 / 2) + (12 / 2) / 3 + 5) * 2).