Expression Evaluation - Infix Postfix
Expression Evaluation - Infix Postfix
Mathematical formulas are usually expressed in what is known as infix notation. In this
form, a binary operation appears between the operands (e.g. a + b). For complex
expressions, parentheses are used to determine the order of evaluation of expressions. For
example, a + (b x c) will yield a different result than (a + b) x c. To minimize the use of
parenthesis, operations have an implied precedence. Generally, multiplication takes
precedence over addition, so that a + b x c is equivalent to a + (b x c).
An alternative technique is known as reverse Polish, or postfix, notation. In this
notation, the operator follows its two operands. For example,
a+b becomes a b +
a + (b x c) becomes a b c x +
(a + b) x c becomes a b + c x
2. If the element is an operator, pop the top two items of the stack, perform the
operation, and push the result.
After the entire expression has been scanned, the result is on the top of the stack.
The simplicity of this algorithm makes it a convenient one for evaluating
expressions. Accordingly, many compilers will take an expression in a high-level
language, convert it to postfix notation, and then generate the machine instructions from
that notation.
For example, the postfix version of (a – b)/(c + d x e) is a b – c d e x + /.
The sequence of operations for evaluating f = (a – b)/(c + d x e) using
a b – c d e x + / are:
1. Push a
2. Push b
3. Subtract
4. Push c
5. Push d
6. Push e
7. Multiply
8. Add
9. Divide
10. Pop f
d
b c c
a a a-b a-b a-b
1 2 3 4 5
e
dx
d e
dxe+
c c c
(a-b)/d x e
a-b a-b a-b +c
6 7 8 9 10
The process of converting an infix expression to a postfix expression is itself most easily
accomplished using a stack. The following algorithm is due to Dijkstra. The infix
expression is scanned from left to right, and the postfix expression is developed and
output during the scan. The steps are as follows:
1. Examine the next element in the input.
2. If it is an operand, output it.
3. If it is an opening parenthesis, push it onto the stack.
4. If it is an operator, then
If the top of the stack is on opening parenthesis, then push the operator.
If it has higher priority than the top of the stack (multiply and divide have
higher priority than add and subtract), then push the operator.
Else, pop operation from stack to output, and repeat step 4.
5. If it is a closing parenthesis, pop operators to the output until an opening
parenthesis is encountered. Pop and discard the opening parenthesis.
6. If there is more input, go to step 1.
7. If there is no more input, pop the remaining operators.