Infix to Postfix Conversion
Postfix notation writes each operator after its operands, so it needs no brackets and no precedence rules. One left-to-right scan with an operator stack converts any infix expression into it.
Infix, Prefix and Postfix Notation
An arithmetic expression can be written in three ways. Infix notation puts the operator between its operands, A + B, and is what people write. Prefix (Polish) notation puts it before, + A B. Postfix (reverse Polish) notation puts it after, A B +.
Infix needs precedence rules and brackets to be unambiguous: A + B * C means A + (B * C) only because * binds tighter. Postfix needs neither. The order of the operators is the order of evaluation, so a computer can evaluate it in one left-to-right pass with a single stack. That is why compilers and calculators convert infix to postfix first.
| Infix | Prefix | Postfix |
|---|---|---|
| A + B | + A B | A B + |
| A + B * C | + A * B C | A B C * + |
| (A + B) * C | * + A B C | A B + C * |
| A − B − C | − − A B C | A B − C − |
| A ^ B ^ C | ^ A ^ B C | A B C ^ ^ |
- Operands keep the same left-to-right order in all three
- Only the operator positions change
- Prefix and postfix never need brackets
Precedence and Associativity Rules
The conversion needs two facts about each operator. Precedence says which of two different operators is applied first. Associativity breaks ties between operators of equal precedence: A − B − C is (A − B) − C because − is left-associative, while A ^ B ^ C is A ^ (B ^ C) because exponentiation is right-associative.
| Operator | Precedence | Associativity |
|---|---|---|
| ^ | 3 (highest) | right to left |
| * / | 2 | left to right |
| + − | 1 (lowest) | left to right |
| ( ) | overrides precedence | not an operator on the stack |
- Higher precedence is applied first, so it is popped first
- Equal precedence, left-associative: the one already on the stack is popped
- Equal precedence, right-associative: the new one is pushed on top
The Stack Method Step by Step
- Operand – append it to the output.
- ( – push it onto the stack.
- ) – pop operators to the output until ( is on top, then pop and discard the (.
- Operator o – while the top is an operator with higher precedence than o, or equal precedence and o is left-associative, pop it to the output. Then push o.
- End of input – pop every remaining operator to the output.
Scan the infix expression from left to right, keeping an output list and an operator stack. Operands are written immediately. Each operator waits on the stack until the scan meets an operator of lower precedence, a closing bracket, or the end of the input, because only then are both of its operands known to be complete. This is Dijkstra's shunting-yard algorithm.
- The stack always holds operators in increasing precedence from bottom to top, between brackets
- A ( is never popped by an operator, only by its matching )
- Time O(n) and space O(n) for n tokens
Terms, operations, and practical uses
Core vocabulary
- InfixOperator between operands: A + B. Needs precedence and brackets.
- PostfixOperator after operands: A B +. Also called reverse Polish notation.
- PrefixOperator before operands: + A B. Also called Polish notation.
- AssociativityWhich side groups first when precedence ties.
Rules
- OperandAppend to output.
- ( and )Push (; on ) pop to ( and discard both.
- OperatorPop higher (or equal and left-associative), then push.
- ComplexityO(n) time, O(n) stack space.
Related lessons
- StacksThe data structure the conversion runs on.
- Expression TreesPrefix, infix and postfix as three traversals of one tree.
- Monotonic StacksAnother stack that pops to keep an ordering invariant.
- StringsScanning and tokenising the expression.
Code in Python, C++ and Java
PRECEDENCE = {"+": 1, "-": 1, "*": 2, "/": 2, "^": 3}
RIGHT_ASSOC = {"^"}
def should_pop(top, op, prefix=False):
if top == "(":
return False
if PRECEDENCE[top] != PRECEDENCE[op]:
return PRECEDENCE[top] > PRECEDENCE[op]
# Equal precedence: left-associative operators pop in postfix. The
# reversed scan used for prefix flips that rule.
return (op in RIGHT_ASSOC) == prefix
def to_postfix(expr, prefix=False, show=False):
stack, out = [], []
for tok in expr.replace(" ", ""):
if tok.isalnum():
out.append(tok)
action = "output operand"
elif tok == "(":
stack.append(tok)
action = "push ("
elif tok == ")":
while stack[-1] != "(":
out.append(stack.pop())
stack.pop()
action = "pop to ("
else:
popped = 0
while stack and should_pop(stack[-1], tok, prefix):
out.append(stack.pop())
popped += 1
stack.append(tok)
action = f"pop {popped}, push {tok}" if popped else f"push {tok}"
if show:
print(f"{tok:<6}{action:<16}{''.join(stack):<8}{' '.join(out)}")
while stack:
out.append(stack.pop())
if show:
print(f"{'end':<6}{'pop the rest':<16}{'':<8}{' '.join(out)}")
return " ".join(out)
def to_prefix(expr):
swapped = {"(": ")", ")": "("}
reversed_expr = "".join(swapped.get(c, c) for c in reversed(expr.replace(" ", "")))
return " ".join(reversed(to_postfix(reversed_expr, prefix=True).split()))
def evaluate_postfix(postfix):
stack = []
for tok in postfix.split():
if tok.isdigit():
stack.append(int(tok))
continue
b, a = stack.pop(), stack.pop()
if tok == "+":
stack.append(a + b)
elif tok == "-":
stack.append(a - b)
elif tok == "*":
stack.append(a * b)
elif tok == "/":
stack.append(a // b)
else:
stack.append(a**b)
return stack[0]
print(f"{'token':<6}{'action':<16}{'stack':<8}output")
to_postfix("A * (B + C) - D / E ^ F", show=True)
print()
examples = ["A + B * C", "(A + B) * C", "A - B - C", "A ^ B ^ C", "A * (B + C) - D / E ^ F"]
for expr in examples:
print(f"{expr:<24} postfix: {to_postfix(expr):<22} prefix: {to_prefix(expr)}")
print()
postfix = to_postfix("(5 + 3) * 2 - 8 / 4")
print(f"(5 + 3) * 2 - 8 / 4 -> {postfix} = {evaluate_postfix(postfix)}")#include <cctype>
#include <cstdio>
#include <map>
#include <string>
#include <vector>
const std::map<char, int> PRECEDENCE = {{'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}, {'^', 3}};
bool shouldPop(char top, char op, bool prefix) {
if (top == '(') return false;
int a = PRECEDENCE.at(top), b = PRECEDENCE.at(op);
if (a != b) return a > b;
// Equal precedence: left-associative operators pop in postfix. The
// reversed scan used for prefix flips that rule.
return (op == '^') == prefix;
}
std::string join(const std::vector<char>& v) {
std::string s;
for (size_t i = 0; i < v.size(); i++) s += (i ? " " : "") + std::string(1, v[i]);
return s;
}
std::string toPostfix(const std::string& expr, bool prefix = false, bool show = false) {
std::vector<char> stack, out;
for (char tok : expr) {
if (tok == ' ') continue;
std::string action;
if (std::isalnum(static_cast<unsigned char>(tok))) {
out.push_back(tok);
action = "output operand";
} else if (tok == '(') {
stack.push_back(tok);
action = "push (";
} else if (tok == ')') {
while (stack.back() != '(') {
out.push_back(stack.back());
stack.pop_back();
}
stack.pop_back();
action = "pop to (";
} else {
int popped = 0;
while (!stack.empty() && shouldPop(stack.back(), tok, prefix)) {
out.push_back(stack.back());
stack.pop_back();
popped++;
}
stack.push_back(tok);
action = popped ? "pop " + std::to_string(popped) + ", push " + tok
: std::string("push ") + tok;
}
if (show) {
std::printf("%-6c%-16s%-8s%s\n", tok, action.c_str(),
std::string(stack.begin(), stack.end()).c_str(), join(out).c_str());
}
}
while (!stack.empty()) {
out.push_back(stack.back());
stack.pop_back();
}
if (show) std::printf("%-6s%-16s%-8s%s\n", "end", "pop the rest", "", join(out).c_str());
return join(out);
}
std::string toPrefix(const std::string& expr) {
std::string reversed;
for (auto it = expr.rbegin(); it != expr.rend(); ++it) {
reversed += *it == '(' ? ')' : *it == ')' ? '(' : *it;
}
std::string post = toPostfix(reversed, true);
return std::string(post.rbegin(), post.rend());
}
int evaluatePostfix(const std::string& postfix) {
std::vector<int> stack;
for (char tok : postfix) {
if (tok == ' ') continue;
if (std::isdigit(static_cast<unsigned char>(tok))) {
stack.push_back(tok - '0');
continue;
}
int b = stack.back();
stack.pop_back();
int a = stack.back();
stack.pop_back();
int r = 1;
switch (tok) {
case '+': r = a + b; break;
case '-': r = a - b; break;
case '*': r = a * b; break;
case '/': r = a / b; break;
default:
for (int i = 0; i < b; i++) r *= a;
}
stack.push_back(r);
}
return stack[0];
}
int main() {
std::printf("%-6s%-16s%-8soutput\n", "token", "action", "stack");
toPostfix("A * (B + C) - D / E ^ F", false, true);
std::printf("\n");
for (std::string expr : {"A + B * C", "(A + B) * C", "A - B - C", "A ^ B ^ C", "A * (B + C) - D / E ^ F"}) {
std::printf("%-24s postfix: %-22s prefix: %s\n", expr.c_str(), toPostfix(expr).c_str(),
toPrefix(expr).c_str());
}
std::printf("\n");
std::string postfix = toPostfix("(5 + 3) * 2 - 8 / 4");
std::printf("(5 + 3) * 2 - 8 / 4 -> %s = %d\n", postfix.c_str(), evaluatePostfix(postfix));
}import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import java.util.Map;
public class Main {
static final Map<Character, Integer> PRECEDENCE = Map.of('+', 1, '-', 1, '*', 2, '/', 2, '^', 3);
static boolean shouldPop(char top, char op, boolean prefix) {
if (top == '(') return false;
int a = PRECEDENCE.get(top), b = PRECEDENCE.get(op);
if (a != b) return a > b;
// Equal precedence: left-associative operators pop in postfix. The
// reversed scan used for prefix flips that rule.
return (op == '^') == prefix;
}
static String join(List<Character> v) {
StringBuilder s = new StringBuilder();
for (int i = 0; i < v.size(); i++) s.append(i > 0 ? " " : "").append(v.get(i));
return s.toString();
}
static String stackText(Deque<Character> stack) {
StringBuilder s = new StringBuilder();
stack.descendingIterator().forEachRemaining(s::append);
return s.toString();
}
static String toPostfix(String expr, boolean prefix, boolean show) {
Deque<Character> stack = new ArrayDeque<>();
List<Character> out = new ArrayList<>();
for (char tok : expr.toCharArray()) {
if (tok == ' ') continue;
String action;
if (Character.isLetterOrDigit(tok)) {
out.add(tok);
action = "output operand";
} else if (tok == '(') {
stack.push(tok);
action = "push (";
} else if (tok == ')') {
while (stack.peek() != '(') out.add(stack.pop());
stack.pop();
action = "pop to (";
} else {
int popped = 0;
while (!stack.isEmpty() && shouldPop(stack.peek(), tok, prefix)) {
out.add(stack.pop());
popped++;
}
stack.push(tok);
action = popped > 0 ? "pop " + popped + ", push " + tok : "push " + tok;
}
if (show) System.out.printf("%-6c%-16s%-8s%s%n", tok, action, stackText(stack), join(out));
}
while (!stack.isEmpty()) out.add(stack.pop());
if (show) System.out.printf("%-6s%-16s%-8s%s%n", "end", "pop the rest", "", join(out));
return join(out);
}
static String toPrefix(String expr) {
StringBuilder reversed = new StringBuilder();
for (int i = expr.length() - 1; i >= 0; i--) {
char c = expr.charAt(i);
reversed.append(c == '(' ? ')' : c == ')' ? '(' : c);
}
return new StringBuilder(toPostfix(reversed.toString(), true, false)).reverse().toString();
}
static int evaluatePostfix(String postfix) {
Deque<Integer> stack = new ArrayDeque<>();
for (String tok : postfix.split(" ")) {
if (Character.isDigit(tok.charAt(0))) {
stack.push(Integer.parseInt(tok));
continue;
}
int b = stack.pop(), a = stack.pop();
stack.push(switch (tok) {
case "+" -> a + b;
case "-" -> a - b;
case "*" -> a * b;
case "/" -> a / b;
default -> (int) Math.pow(a, b);
});
}
return stack.pop();
}
public static void main(String[] args) {
System.out.printf("%-6s%-16s%-8soutput%n", "token", "action", "stack");
toPostfix("A * (B + C) - D / E ^ F", false, true);
System.out.println();
for (String expr : List.of("A + B * C", "(A + B) * C", "A - B - C", "A ^ B ^ C", "A * (B + C) - D / E ^ F")) {
System.out.printf("%-24s postfix: %-22s prefix: %s%n", expr, toPostfix(expr, false, false), toPrefix(expr));
}
System.out.println();
String postfix = toPostfix("(5 + 3) * 2 - 8 / 4", false, false);
System.out.printf("(5 + 3) * 2 - 8 / 4 -> %s = %d%n", postfix, evaluatePostfix(postfix));
}
}Step through it
Running on A * (B + C) - D / E ^ F
Worked Example: A * (B + C) − D / E ^ F
The tracer above converts A * (B + C) − D / E ^ F one token at a time. Three moments decide the answer. The ) pops + and throws both brackets away. The − finds * on the stack and pops it first, because multiplication happens before subtraction. At the end, − / ^ are still waiting, in rising precedence, and leave top first: ^, then /, then −.
- Postfix: A B C + * D E F ^ / −
- 13 input tokens, 11 output tokens: the two brackets disappear
- Operators leave in the order they are evaluated: +, *, ^, /, −
Postfix Evaluation
Postfix evaluation uses a stack of values. Scan left to right: push each operand; for each operator, pop two values, apply the operator (the first value popped is the right operand), and push the result. At the end the stack holds exactly one value, the answer.
For (5 + 3) * 2 − 8 / 4, the postfix is 5 3 + 2 * 8 4 / −. The stack goes 5, 5 3, 8, 8 2, 16, 16 8, 16 8 4, 16 2, 14. The answer is 14, found without any precedence rules.
- Operand: push; operator: pop b, pop a, push a op b
- Order matters for − and /: it is a − b, not b − a
- Practise: Evaluate Reverse Polish Notation
Infix to Prefix Conversion
- Reverse the infix string and swap each ( with ).
- Convert with the postfix algorithm, flipping the equal-precedence rule.
- Reverse the output to get prefix.
Prefix can be produced with the same stack algorithm by working backwards. Reverse the infix expression, swap ( and ), run the postfix algorithm with the tie rule flipped (equal-precedence left-associative operators are pushed, not popped), and reverse the result.
For A * (B + C) − D / E ^ F this gives − * A + B C / D ^ E F. The flipped tie rule matters: without it, A − B − C would come out as − A − B C, which means A − (B − C).
- Prefix evaluation scans right to left with a value stack
- The expression tree gives all three notations from one structure
Common Mistakes
Most wrong answers come from the equal-precedence case or from brackets. Check each of these when working by hand in an exam.
- Ties with − or /: A − B − C is A B − C −; pushing without popping gives A B C − −, which means A − (B − C)
- Ties with ^: A ^ B ^ C is A B C ^ ^; popping the first ^ gives A B ^ C ^, which means (A ^ B) ^ C
- Popping past a (: an operator inside brackets never pops what is below the (
- Brackets in the output: they are discarded, never written
- Operand order in evaluation: for 8 4 / the first value popped is the divisor, so the result is 8 / 4
- Related: build the expression tree and read it three ways
- Practise the conversion: Infix to Postfix
- The stack itself: Stacks