Expression conversion and evaluation
Postfix needs one stack: push numbers, and an operator pops two, applies, and pushes the result. Normal (infix) expressions need two stacks, numbers and operators. Before pushing an operator, apply every waiting operator of equal or higher precedence. Brackets act as walls.
How to recognise it
- The input is an arithmetic expression as a string.
- You must evaluate it, or turn it into postfix or prefix.
- Precedence and brackets decide the order of work.
Three ways to write the same thing
| Name | Example | Operators come |
|---|---|---|
| infix | (2 + 3) * 4 | between operands |
| postfix | 2 3 + 4 * | after operands |
| prefix | * + 2 3 4 | before operands |
Postfix and prefix need no brackets: the order of the operators already says what happens first.
Evaluating postfix
Read tokens left to right. Push numbers. For an operator, pop b, then pop a, and push a op b. The single number
left is the answer. Prefix is the same scanned from the right, and there the first number popped is the left operand.
Evaluating infix (two stacks)
for each token:
number -> push to nums
'(' -> push to ops
')' -> apply ops until '('; drop '('
operator -> while the top op is not '(' and has precedence >= this one: apply it
push this operator
apply what is left
"Apply" pops one operator and two numbers and pushes the result. The same loop with an output list instead of nums
converts infix to postfix (this is the shunting-yard method).
Common mistakes
- Swapping the operands of
-and/. - Reading
12as two numbers: keep reading digits. - Rounding division the wrong way: in Java, C++ and this guide, integer division goes towards zero; Python's
//does not, so useint(a / b).
Problems
- Arithmetic Expression evaluationmediumguide ready
- Evaluation of Postfix expressionmediumguide ready