Postfix to Infix is a common problem in data structure field. In our daily life, Postfix expression is used most frequently. However, digital machines execute each expression in infix format. Thus, this is important to know the conversion mechanism in detail. Dijkstra proposed a subtle algorithm, known as Shunting Yard algorithm, that works efficiently to determine postfix expression values into infix format. A program is shown below based on Shunting Yard algorithm that evaluates an expression and find the final value. The full pseudo code can be found here: http://en.wikipedia.org/wiki/Shunting-yard_algorithm
At first we need to understand what is postfix and infix expression.
Postfix Expression: (2+3) * 5 + (3*4)
Infix Expression: 2 3 + 5 * 3 4 * +
Here, division and multiplication operators have same precedence as well as greater precedence than plus and minus operators.
The pseudo code is given below:
- 1.While there are input symbol left
- 2. Read the next symbol from input.
- 3. If the symbol is an operand
- Push it onto the stack.
- 4. Otherwise,
- the symbol is an operator.
- 5. If there are fewer than 2 values on the stack
- Show Error /* input not sufficient values in the expression */
- 6. Else
- Pop the top 2 values from the stack.
- Put the operator, with the values as arguments and form a string.
- Encapsulate the resulted string with parenthesis.
- Push the resulted string back to stack.
- 7. If there is only one value in the stack
- That value in the stack is the desired infix string.
- 8. If there are more values in the stack
- Show Error /* The user input has too many values */
A sample C code is given below:
মন্তব্যসমূহ
একটি মন্তব্য পোস্ট করুন