Conceptual
Login

Evaluating Prefix and Postfix Expressions with a Stack in Data Structures

Postfix (reverse Polish) and prefix (Polish) notations place the operator after or before its operands respectively, encoding operator precedence positionally so that no parentheses are required, and both can be evaluated in a single linear scan using a stack. The governing rule is that operands accumulate on a last-in-first-out structure until an operator token is read, at which point exactly as many operands as the operator's arity are popped, the operation applied, and the result pushed back as a reduced operand; a well-formed expression terminates with exactly one value on the stack, which is the result. The two notations differ only in scan direction — postfix is scanned left to right and prefix right to left — and in the order in which popped values map to operand positions, which matters for non-commutative operators; this belongs to the data structures and algorithms subfield of computer science, specifically stack applications and expression parsing.