Data Structures and Algorithms
The expression “3 4 + 2 * 5 −” in reverse Polish notation (postfix notation) is evaluated by pushing each number onto a stack and, for each operator, popping two values, computing the result and pushing it back. What is the result? The left operand of an operator is the value that was pushed earlier.
- A−9
- B6
- C9
Show answer and explanation
Answer: C. 9
Push 3 and 4, then + pops them and pushes 3 + 4 = 7. Push 2, then * pushes 7 × 2 = 14. Push 5, then − subtracts the later value 5 from the earlier value 14, giving 14 − 5 = 9. In postfix notation the order of operations is fixed by the sequence itself, so no parentheses are needed; this expression corresponds to (3 + 4) × 2 − 5 in ordinary notation. −9 results from swapping the operands of the subtraction, and 6 from reading it as 3 + 4 × 2 − 5 without parentheses.
- A. This swaps the operands of the subtraction (5 − 14). The left operand is 14, which was pushed earlier.
- B. This computes 3 + 4 × 2 − 5 without parentheses. In postfix notation the + is done first.
- C. Correct. (3 + 4) × 2 − 5 = 9.