4.3Stack Applications
Converting infix to postfix
You write A*(B+C)-D, but a calculator or a compiler first turns that expression into a form without parentheses. In that form each operator comes after its operands, and the value is computed in one left-to-right pass. The algorithm that does the conversion keeps operators waiting on a stack.
- The difference between infix, postfix and prefix notation
- How to convert infix to postfix by handling operator precedence and parentheses with a stack
- The full-parenthesis method for converting by hand in an exam
1Idea
In infix notation the operator sits between its two operands: A*(B+C)-D. It is easy to read, but to compute it you need to know precedence and parentheses. In postfix notation the operator comes after its operands: ABC+*D-. No parentheses are needed, and as the next lesson shows, it is computed with a stack in one left-to-right pass. The conversion method in this lesson is Dijkstra's shunting-yard algorithm.
Operands (letters or digits) go straight to the output in the order they arrive; their order never changes. Only operators wait, and the waiting place is a stack. Each character read is one of four kinds:
- An operand is written straight to the output.
- A
(is pushed onto the stack. It acts as a fence; no operator can pop it. - On a
), operators are popped and written to the output until(shows up, then the(is dropped. Parentheses never reach the output. - On an operator, as long as the operator on top has higher or equal precedence than the incoming one, the top is popped and written out. When the top is a lower-precedence operator or
(, or the stack is empty, it stops and pushes the incoming operator.
When the input ends, the operators left on the stack are popped one by one and added to the output. Here * and / have precedence 2, + and - have precedence 1. Popping on equal precedence too makes the operators associate from the left: A-B-C means (A-B)-C and becomes AB-C-.
The power operator ^ is right-associative: A^B^C means A^(B^C), and its postfix is ABC^^. So when the incoming operator is ^, the top is popped only if its precedence is strictly higher. The code here does not handle ^.
The code assumes the input is a valid expression; you can check the parentheses first with balanced parentheses. Spaces are skipped. The stack can be the one you built with an array or with a linked list; both do the same job. To keep the code short, C uses a local array, Java uses java.util.ArrayDeque, and Python uses a list. The C version writes the result into the postfix array the caller passes in.
Converting by hand: full parenthesization
When you convert on paper in an exam, this method is faster than tracing a stack:
- Fully parenthesize the expression by precedence: put every operator with its two operands inside a pair of parentheses. For
A*(B+C)-Dthat gives((A*(B+C))-D). - Move each operator to the place of the closing parenthesis of its own pair.
- Delete all the parentheses. The result:
A B C + * D -.
The same method gives prefix notation: move each operator to its opening parenthesis instead of the closing one. For ((A*(B+C))-D) the result is - * A + B C D. Prefix needs no parentheses either; this time the expression is computed with a stack by reading it from right to left.
2Step by step
The drawing converts A*(B+C)-D to postfix. The top row is the input, the bottom row is the output; i marks the character being read. The stack under the drawing holds the waiting operators; the bottom line is the top.
- Start. The input is
A*(B+C)-D; the stack and the output are empty. Ais an operand. It goes to the output without waiting; the stack does not change.*is an operator. The stack is empty, so there is nothing to pop;*is pushed.(is pushed.*is now under it; until the parenthesis closes,(stands like a fence.Bis an operand and goes to the output. Output:AB.+is an operator. The top is(, and no operator can pop it.+is pushed.Cis an operand and goes to the output. Output:ABC.)arrives. Pop until(shows up:+goes to the output. Then(is popped and dropped. The top is*again.-is an operator with precedence 1. The*on top has precedence 2, which is higher:*is popped and written out. The stack is empty;-is pushed.Dis an operand and goes to the output. Output:ABC+*D.- The input has ended. The
-left on the stack is popped and added to the output. Result:ABC+*D-.
int precedence(char op) { if (op == '*' || op == '/') return 2; if (op == '+' || op == '-') return 1; return 0; // 0 for '(': no operator can pop it} void toPostfix(const char* infix, char* postfix) { char stack[strlen(infix) + 1]; // operator stack int top = -1, k = 0; // k: next free place in the output for (int i = 0; infix[i] != '\0'; i++) { char c = infix[i]; if (c == ' ') continue; if (c == '(') { stack[++top] = c; // push } else if (c == ')') { while (stack[top] != '(') // until '(' shows up postfix[k++] = stack[top--]; // pop, write to output top--; // drop the '(' } else if (precedence(c) > 0) { while (top >= 0 && precedence(stack[top]) >= precedence(c)) postfix[k++] = stack[top--]; // pop higher or equal precedence stack[++top] = c; // push } else { postfix[k++] = c; // operand goes straight out } } while (top >= 0) // remaining operators postfix[k++] = stack[top--]; postfix[k] = '\0';}int precedence(char op) { if (op == '*' || op == '/') return 2; if (op == '+' || op == '-') return 1; return 0; // 0 for '(': no operator can pop it} String toPostfix(String infix) { java.util.ArrayDeque<Character> stack = new java.util.ArrayDeque<>(); // operator stack StringBuilder output = new StringBuilder(); for (int i = 0; i < infix.length(); i++) { char c = infix.charAt(i); if (c == ' ') continue; if (c == '(') { stack.push(c); } else if (c == ')') { while (stack.peek() != '(') // until '(' shows up output.append(stack.pop()); // pop, write to output stack.pop(); // drop the '(' } else if (precedence(c) > 0) { while (!stack.isEmpty() && precedence(stack.peek()) >= precedence(c)) output.append(stack.pop()); // pop higher or equal precedence stack.push(c); } else { output.append(c); // operand goes straight out } } while (!stack.isEmpty()) // remaining operators output.append(stack.pop()); return output.toString();}PRECEDENCE = {"+": 1, "-": 1, "*": 2, "/": 2} def to_postfix(infix): stack = [] # operator stack output = [] for c in infix: if c == " ": continue if c == "(": stack.append(c) # push elif c == ")": while stack[-1] != "(": # until "(" shows up output.append(stack.pop()) # pop, write to output stack.pop() # drop the "(" elif c in PRECEDENCE: while stack and PRECEDENCE.get(stack[-1], 0) >= PRECEDENCE[c]: output.append(stack.pop()) # pop higher or equal precedence stack.append(c) else: output.append(c) # operand goes straight out while stack: # remaining operators output.append(stack.pop()) return "".join(output)The snippets focus on the operation in this lesson. The C examples need stdlib.h.
3Complexity
Each character is read once. Each operator enters the stack at most once and leaves once; the inner while loops never add up to more than n turns.
In the worst case (like ((((A))))) most characters wait on the stack; the output is n long as well.
Because of the inner while loop it looks like O(n²) at first. But each turn of that loop pops one operator, and each operator can be popped only once. So all the loops together are bounded by n turns.
4Common mistake
The most common mistake is writing > instead of >= in the operator comparison:
while (top >= 0 && precedence(stack[top]) > precedence(c)) // wrong: equal precedence is not poppedOperators of equal precedence then pile up on the stack. For A-B-C the output becomes ABC--, which means A-(B-C): 8-4-2 gives 6 instead of 2. With left-associative operators, a top of equal precedence must be popped too.
5Try it
What is the postfix form of A+B*C?
The answer is B. While + waits on the stack, * arrives. * has higher precedence, so + is not popped and * is pushed on top of it. When the input ends, * comes off first and then +: ABC*+.
Show the answer
The answer is B. While + waits on the stack, * arrives. * has higher precedence, so + is not popped and * is pushed on top of it. When the input ends, * comes off first and then +: ABC*+.
What is the prefix form of (A+B)*C?
The answer is A. Fully parenthesize: ((A+B)*C). Move each operator to its opening parenthesis and delete the parentheses: * + A B C. The third option is the postfix form of the same expression.
Show the answer
The answer is A. Fully parenthesize: ((A+B)*C). Move each operator to its opening parenthesis and delete the parentheses: * + A B C. The third option is the postfix form of the same expression.
Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.