How can you convert an infix expression to postfix expression using stack? Give one example.
Q.) How can you convert an infix expression to postfix expression using stack? Give one example.
Subject: Data StructuresInfix notation is the common arithmetic and logical formula notation, in which operators are written infix-style between the operands they act on (e.g. 2 + 3). Postfix notation, also known as "Reverse Polish notation", is a mathematical notation in which every operator follows all of its operands (e.g. 2 3 +).
To convert an infix expression to a postfix expression, we can use a stack. Here are the steps:
- Scan the infix expression from left to right.
- If the scanned character is an operand, output it.
- Else,
- If the precedence of the scanned operator is greater than the precedence of the operator in the stack(or the stack is empty), push it.
- Else, Pop the operator from the stack until the precedence of the scanned operator is less-equal to the precedence of the operator residing on the top of the stack. Push the scanned operator to the stack.
- If the scanned character is an '(', push it to the stack.
- If the scanned character is an ')', pop and output from the stack until an '(' is encountered. Pop the '(' from the stack, but do not output it.
- Repeat steps 2-6 until infix expression is scanned.
- Print the output
- Pop and output from the stack until it is not empty.
Let's take an example to convert infix expression to postfix:
Infix expression: A + B * C
Step 1: Scan the infix expression from left to right. (A + B * C)
Step 2: If the scanned character is an operand, output it. (A)
Step 3: Else, If the precedence of the scanned operator is greater than the precedence of the operator in the stack(or the stack is empty), push it. (+)
Step 4: If the scanned character is an operand, output it. (B)
Step 5: Else, If the precedence of the scanned operator is greater than the precedence of the operator in the stack(or the stack is empty), push it. (*)
Step 6: If the scanned character is an operand, output it. (C)
Step 7: Pop and output from the stack until it is not empty. (+ *)
So, the postfix expression is: A B C * +
Here is a table showing the precedence of operators:
Operator | Precedence |
---|---|
+, - | Lowest |
*, / | Medium |
^ | Highest |
(, ) | N/A |
- The precedence of '(' & ')' is not defined and they are never compared with each other or with any other operators.
- The precedence of operators is used to determine the order of operations in an expression.
- The higher the precedence, the earlier an operator is applied in an expression.