Infix to Postfix Visualizer
What is Postfix Notation?
Postfix notation (also called Reverse Polish Notation) is a way of writing expressions where the operator comes after the operands.
For example, the infix expression 3 + 4 becomes 3 4 + in postfix.
It removes the need for parentheses by making operator precedence explicit through position.
Infix to Postfix Conversion Steps
- Initialize an empty stack and an empty output string.
- Scan the infix expression from left to right.
- If the element is an operand, add it to the output.
- If the element is a '(', push it onto the stack.
- If the element is a ')', pop from the stack and add to output until '(' is encountered.
- If the element is an operator, pop from the stack all operators with higher or equal precedence, then push the current operator.
- After scanning, pop all remaining operators from the stack.
Example:
Infix: (A + B) * (C - D)
Step 1: Push '(' → Stack: [ '(' ], Output: ''
Step 2: Add 'A' → Output: 'A'
Step 3: Push '+' → Stack: [ '(', '+' ]
Step 4: Add 'B' → Output: 'A B'
Step 5: Pop until '(' → Stack: [ ], Output: 'A B +'
Step 6: Continue similarly for the rest → Final Postfix: A B + C D - *
Operator Precedence Table
Operator | Meaning | Precedence |
---|---|---|
( ) | Parentheses | Highest |
^ % | Exponentiation / Modulus | 2 |
* / | Multiplication / Division | 3 |
+ - | Addition / Subtraction | 4 (Lowest) |
Note: Higher precedence means the operation will happen first. When operators have equal precedence, they are evaluated left-to-right (except for exponentiation which is right-to-left).
Visualize the conversion from infix to postfix notation
Conversion Status
Enter an infix expression and click Convert
Stack
Stack is empty
Output
Output will appear here
Postfix Evaluation using Stack
// Postfix Evaluation using Stack (JavaScript)
function evaluatePostfix(expression) {
let stack = [];
for (let char of expression) {
if (!isNaN(char)) {
stack.push(parseInt(char));
} else {
const b = stack.pop();
const a = stack.pop();
switch(char) {
case '+': stack.push(a + b); break;
case '-': stack.push(a - b); break;
case '*': stack.push(a * b); break;
case '/': stack.push(Math.floor(a / b)); break;
}
}
}
return stack.pop();
}
// Example: "23*5+" becomes (2*3)+5 = 11
console.log(evaluatePostfix("23*5+")); // Output: 11