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 equivalent to P.
- Stack: Create an empty stack.
- 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.
- If T is an operand (e.g., a digit):
- Repeat step 4 for all tokens in P.
- 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:
- Push 12 onto the stack.
- Push 7 onto the stack.
- Push 3 onto the stack.
- Pop the top two operands from the stack (7 and 3) and concatenate them with the division operator (/) to form 7/3.
- Push 7/3 onto the stack.
- Push . onto the stack.
- Push 2 onto the stack.
- Pop the top two operands from the stack (2 and .) and concatenate them with the multiplication operator (*) to form 2..
- Push 2* onto the stack.
- Pop the top two operands from the stack (7/3 and 2*) and concatenate them with the addition operator (+) to form (7/3) + (2*).
- Push (7/3) + (2*) onto the stack.
- Push 5 onto the stack.
- 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.
- Push ((7/3) + (2*)) * 5 onto the stack.
- Pop the top two operands from the stack (((7/3) + (2*)) * 5) and +) to form (((7/3) + (2*)) * 5) + .
- The top of the stack now contains the infix expression equivalent to P: ((7/3) + (2*)) * 5 + .
Final Answer:
(((7/3) + (2*)) * 5) +