Dynamic programming · Exercise 72 of 100
Postfix evaluation
In postfix notation, an operator follows the values it acts on. Read left to right and put each number on a stack, where the last value added is the first one removed. For an operator that needs two values, remove the right operand first and the left operand second, then put the result back so a later operator can use it.
Try it yourself
What value does the postfix expression 9 2 3 + - produce?
One-step hint
Stack the numbers until you reach +. Push its result back, then use the first value popped at the minus sign as the right operand.
Worked solution
- Put 9, 2, and 3 on the stack. The plus sign combines 2 and 3, leaving 9 with 5 above it.
- The minus sign takes 5 as its right operand and 9 as its left, so the result is 9 - 5 = 4.