CIE AS & A Level Computer Science, section 16.2 (Translation software)
What RPN is
Reverse Polish Notation (RPN, postfix) writes the operator after its operands, so no brackets are needed.
| Infix | RPN |
|---|---|
3 4 + |
|
3 4 + 2 * |
|
5 1 2 + 4 * + 3 - |
Why it is used
A compiler (or interpreter) converts expressions to RPN because it is easy to evaluate using a stack, and the order of calculation is clear with no brackets or precedence rules.
Evaluating RPN with a stack
Read each item from left to right.
- If it is an operand, push it.
- If it is an operator, pop two values, apply the operator (the first popped is the right-hand operand), and push the result.
Example: 3 4 + 2 *
| Item | Stack after |
|---|---|
| 3 | 3 |
| 4 | 3, 4 |
| + | 7 |
| 2 | 7, 2 |
| * | 14 |
The result is 14.
Converting infix to RPN
Work from the highest precedence operator. Brackets first, then * and /, then + and -. The shunting-yard method uses an operator stack.
Common mistake: swapping the operands for - and /. The second value popped is the left operand, so for 8 2 - the answer is , not . Also, RPN has the operator after its operands.
Exam tip: show a stack table with each item and the stack after it. For conversion, work out the order of calculation first, then write operands followed by each operator.
Check yourself
Write in RPN.
2 5 + 3 *.
Evaluate `6 2 /` using a stack.
Push 6 and 2; pop 2 and 6 and calculate , giving 3.
Why does RPN not need brackets?
The position of each operator after its operands fixes the order of calculation.