LearnWave
Learn it. Master it.

Stack

Evaluating postfix

Evaluate postfix expressions step by step.

A postfix expression is easy to evaluate with a stack. Read it from left to right:

  • When you read an operand, PUSH it onto the stack.
  • When you read an operator, POP two elements, apply the operator to them (the second one popped is the left operand), and PUSH the result back.

So, unlike in conversion, here only operands (and results) are pushed.

At the end, if exactly one element is left on the stack, it is the answer. If more than one is left, the expression was invalid.

Example: evaluate 6 2 3 + × 4 −.

  • Push 6, 2 and 3: the stack is [6, 2, 3].
  • + pops 3 and 2, and pushes 2 + 3 = 5: [6, 5].
  • × pops 5 and 6, and pushes 6 × 5 = 30: [30].
  • Push 4: [30, 4].
  • − pops 4 and 30, and pushes 30 − 4 = 26: [26].

One element remains, so the value of the expression is 26.

Push operands; an operator pops two and pushes the result.
Push operands; an operator pops two and pushes the result.

Practise this lesson

Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.

No account, no email address. Opens the real product.