Topic 4
Infix to Postfix Conversion
Expression Conversion using Stack
Infix: Operators are between operands. e.g., A + B * C
Postfix: Operators are after operands. e.g., A B C * + (Computers love this because it removes the need for parentheses and precedence rules).
We use a Stack to temporarily hold operators and left parentheses while we process the expression from left to right.
Algorithm Rules
- If character is an Operand (A-Z, 0-9): Add it directly to the Postfix string.
- If character is a Left Parenthesis '(': Push it onto the stack.
- If character is a Right Parenthesis ')': Pop operators from the stack and add to Postfix until a '(' is found. Discard the '(' and ')'.
- If character is an Operator (+, -, *, /, ^):
- While stack is not empty and precedence of top operator >= precedence of current operator, Pop and add to Postfix.
- Then Push the current operator onto the stack.
- At end of expression, Pop any remaining operators from the stack into Postfix.
โ๏ธ
Precedence:
^ (Highest) > * , / > + , - (Lowest)๐ฆ
Stack only holds: Operators and Parentheses. Operands NEVER go into the stack for this conversion.
infix-postfix