Learn / Stacks and queues

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

NameExampleOperators come
infix(2 + 3) * 4between operands
postfix2 3 + 4 *after operands
prefix* + 2 3 4before 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 12 as 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 use int(a / b).

Problems

0 of 2 solved

Check yourself

What is the value of the postfix expression 2 3 1 * + 9 -?

In postfix evaluation, which popped number is the right operand?

While scanning 10 - 2 - 3, when the second '-' arrives, what happens to the first?

What does '(' do on the operator stack?