awelgorithms

Evaluate postfix with a stack

Updated

Scan tokens left to right: operand → push; operator → pop two, apply, push. At the end the stack holds exactly one value: the answer.

What to focus on

"2 3 + 4 *" : (2+3)*4 = 20. No precedence parsing. The postfix order already encoded it. Parentheses do not appear in postfix.

Worked examples

sum then mul

s = "2 3 + 4 *"
  1. [2,3] → [5] → [5,4] → [20]

Result: 20

mul first

s = "2 3 4 * +"
  1. [2,3,4] → [2,12] → [14]

Result: 14

single

s = "7"
  1. push 7
  2. one value left

Result: 7

Try it

Write evalPostfix(s). s is well-formed postfix of integers and + − *. Scan tokens: push operands; on an operator pop two, apply, push. End with exactly one stack item. "2 3 + 4 *" → 20. "2 3 4 * +" → 14. "7" → 7.

s is well-formed postfix of integers and + − *. The stack always has two operands when an operator arrives, and ends with one value.