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
Token "2" is a number. Push 2 onto the stack. Stack: [2]
1FUNCTION evalRpn(tokens):2 make an empty stack3 FOR each token tok in tokens:4 IF tok is a number: push tok onto the stack5 ELSE:6 pop the top of the stack into b7 pop the next top into a8 CHECK the operator tok:9 if '+': push a + b10 if '-': push a - b11 if '*': push a * b12 if '/': push a / b truncated toward zero13 END CHECK14 END IF15 END FOR16 RETURN the only value left on the stack
← / → step · space play · Home restart