Infix and Postfix Expressions
Infix and Postfix Expressions
In a postfix expression,
• an operator is written after its operands.
• the infix expression 2+3 is 23+ in postfix notation.
• For postfix expressions, operations are performed in the order in which they are
written (left to right).
• No parentheses are necessary. ‘
• the infix expression 2+3*4 is 234*+ in postfix notation
• the infix expression 3*4+2*5 translates to 34*25*+ in postfix notation.
• the infix expression 3*(4+2)*5 translates to 342+*5*
Look at 234*+.
Here is the sequence of operations:
• 234*+ * is the first operator. Perform the operation 34*
• 2 12 + 3 4*is replaced by 12 , the value of 3*4
+ is next operator, perform 2 12+
• replace 2 12+ with 14. Done
1
• When you are finished scanning the expression, the final value remains on the
stack.
Input Stack
34*25*+ empty Push 3
4*25*+ 3 Push 4
*25*+ 43 Pop 4, pop 3, do 3*4, Push 12
25*+ 12 Push 2
5*+ 2 12 Push 5
*+ 5 2 12 Pop 5, Pop 2, do 2*5, Push 10
+ 10 12 Pop 10, Pop 12 do 12 + 10, push 22
22
Thus a typical input string is 23*73/+, which in infix notation is 2*3 + 7/3 (value is 8).
2
How to convert Infix to postfix.
Also, since our four operators are left associative, 2 + 3 + 4 translates to 23+4+ and not
234++. While both of these postfix expressions evaluate to 7, the first is interpreted as
(2+3)+4 (correct) and the second as 2 + (3+4) (incorrect associativity). By ignoring the
associativity of operators, you could run into trouble with subtraction and division. The
infix expression 2-3+4 is evaluated as (2-3)+4 = (-1)+4 = 3. The correct postfix is 23-4+
and not 234+- (which is equivalent to 2- (3+4) and evaluates to -5).
Once again, we can use a stack to facilitate the conversion of infix to postfix.
This time, however, we will use a stack of characters to store the operators in the
expression. To convert correctly formed infix expressions to postfix we will use the
following algorithm.
3
Examples.
Input Stack Postfix
2*3 + 4*5 empty
*3+4*5 empty 2
3+4*5 * 2
+4*5 * 23
4*5 + 23*
*5 + 23*4
5 *+ 23*4
*+ 23*45
+ 23*45*
empty 23*45*+