Algorithms / Stack Expression Evaluation
Least You Need to Know: Stacks, Postfix Evaluation, and Expression State
Stacks evaluate postfix expressions because operands arrive before the operator that combines them. When the operator appears, the most recent operands are popped, combined, and the result is pushed back for later use.
The least you need to know
- Postfix notation places operators after their operands.
- Operands are pushed as they appear.
- When an operator appears, pop the required operands, apply the operator, and push the result.
- Operand order matters for subtraction and division.
- A valid postfix evaluation usually finishes with exactly one value on the stack.
Key notation
postfix
operator comes after its operands
push operand
store a numeric value for later combination
pop right then left
preserve operand order for noncommutative operators
Tiny worked example
- For `2 3 + 4 *`, push 2, push 3, then `+` pops 3 and 2 and pushes 5.
- Then push 4.
- `*` pops 4 and 5 and pushes 20.
- The final stack value is the expression result.
Common mistakes
- Students sometimes pop operands in the wrong order for subtraction or division.
- Each operator reduces the number of stack items by one in binary-operator expressions.
- A correct final evaluation should leave one result, not many leftovers.
How to recognize this kind of problem
- The expression is postfix or reverse-polish notation.
- The prompt says to evaluate while reading tokens left to right.
- Operators combine the most recently available operands.