In mathematics and computer science, infix, postfix, and prefix notations are three different but equivalent ways of writing expressions. Each notation has its own rules for the order and placement of operators and operands.
Definition: In infix notation, operators are written in-between their operands. This is the most common way of writing expressions that we use in arithmetic and algebra.
A + B
(3 + 4) * 5
Requires rules for operator precedence (which operator should be evaluated first) and associativity (the order in which operations of the same precedence are performed) to avoid ambiguity.
Parentheses are often used to enforce the order of operations.
Definition: In postfix notation, the operator is placed after their operands.
A B +
3 4 + 5 *
Does not need any parentheses or operator precedence rules to determine the order of operations; the order is entirely determined by the position of the operators and operands.
Can be easily evaluated using a stack; push operands onto the stack, and when an operator is encountered, pop operands for the operation from the stack and push the result back onto the stack.
Definition: In prefix notation, the operator is placed before their operands.
+ A B
* + 3 4 5
Like postfix, prefix notation does not require parentheses and precedence rules.
Evaluation can be done using a stack but typically requires reading the expression from right to left or using a more complex algorithm for left-to-right evaluation.
Call Stack: Stacks are used to keep track of function calls in most programming languages. Each function call creates a frame on the stack with its parameters and local variables. When a function returns, its frame is popped off the stack.
Handling Recursion: Recursion naturally fits the LIFO structure of stacks. Each recursive call uses a new stack frame, and returning from a call removes the frame.
Infix to Postfix/Prefix Conversion: Stacks are used to convert expressions from infix notation to postfix or prefix notations, which are easier for computers to evaluate.
Postfix/Prefix Expression Evaluation: Stacks make it easy to evaluate postfix or prefix expressions. Operands are pushed onto the stack, and when an operator is encountered, the relevant operands are popped, the operation is executed, and the result is pushed back.