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 AlgorithmAlgorithm for Postfix to Infix Conversion:
- Input: A postfix expression P.
- Output: An infix expression Q.
- Stack S: Initialize an empty stack S.
- 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.
- Pop the top element from S. This is the infix expression Q.
- 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:
- Initialize the stack S: S = {}
- Read the first character from P: x = 1
- Since x is an operand, push it onto S: S = {1}
- Read the second character from P: x = 2
- Since x is an operand, push it onto S: S = {1, 2}
- Read the third character from P: x = 7
- Since x is an operand, push it onto S: S = {1, 2, 7}
- 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)"}
- 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)"}
- Read the sixth character from P: x = 3
- Since x is an operand, push it onto S: S = {"(12 / 2)", 3}
- 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)"}
- 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)"}
- 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)"}
- 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)"}
- 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).