Visualize

Pattern visualizer

Evaluate Reverse Polish Notation

The key insight: RPN encodes evaluation order without needing parentheses or precedence rules — every operator appears immediately after the two operands it applies to. A stack captures exactly that for free: push operands as you see them, and the moment you hit an operator, the two values it needs are automatically the last two things pushed. Pop the two most recent operands, apply the operator, and push the result back so it's ready for whatever operator comes next. Animated on: Evaluate the expression tokens = ["2","1","+","3","*"] = (2+1)*3 = 9..

Stack

step 1 / 6
2
[0]
line 2

Token "2" is a number. Push 2 onto the stack. Stack: [2]

Pseudocode
1FUNCTION evalRpn(tokens):
2 make an empty stack
3 FOR each token tok in tokens:
4 IF tok is a number: push tok onto the stack
5 ELSE:
6 pop the top of the stack into b
7 pop the next top into a
8 CHECK the operator tok:
9 if '+': push a + b
10 if '-': push a - b
11 if '*': push a * b
12 if '/': push a / b truncated toward zero
13 END CHECK
14 END IF
15 END FOR
16 RETURN the only value left on the stack

← / → step · space play · Home restart

Where to practice Stack