4.3Stack Applications
Evaluating a postfix expression
In the previous lesson we turned an infix expression into postfix form, which has no parentheses. Now that form pays off: a postfix expression is computed with a single stack by reading it once from left to right. It needs no precedence rules and no parentheses.
1Idea
In a postfix expression the operator comes after its operands. So when an operator is read, its two operands have already been read, and they are the most recent ones. Handing back the most recent item first is exactly what a stack does.
The algorithm reads the expression once, left to right. When a digit arrives, it turns it into a number and pushes it. When an operator arrives, it does two pops, applies the operation and pushes the result back. When the expression ends, one number is left on the stack; that number is the result.
The pop order matters. The first pop gives the right operand, the second gives the left operand. It makes no difference for addition and multiplication, but it changes the result for subtraction and division: for 82- the left is 8, the right is 2, and the result is 6, not -6.
The expression 6324+-* in the drawing means 6*(3-(2+4)) in infix. A second example is 23*54*+9-: first 2*3 = 6, then 5*4 = 20, then 6+20 = 26, and finally 26-9 = 17.
Division is integer division. C and Java truncate the result toward zero: -5/2 is -2. Python's // operator rounds down instead and gives -3. So that all three languages agree, the Python code uses int(left / right).
The code assumes the input is valid: operands are single digits, spaces are skipped, and division by zero is not checked. In an incomplete expression like 2+, the second pop meets an empty stack (an underflow); a real calculator reports this as an error.
The stack can be the one you built with an array or with a linked list; the algorithm only needs push and pop. To keep the code short, C uses a local array, Java uses java.util.ArrayDeque, and Python uses a list.
2Step by step
The drawing evaluates 6324+-*. i marks the character being read. The stack under the drawing holds the numbers; the bottom line is the top. Under each operator you see the operation it performed.
- Start. The expression is
6324+-*and the stack is empty. 6is a digit. It is turned into a number and pushed.3is a digit too and is pushed. The top is 3.2is pushed.4is pushed. There are four numbers on the stack; the top is 4.+is an operator. The first pop gives 4 (right), the second gives 2 (left).2+4 = 6is computed and 6 is pushed.- The
-operator. The first pop gives 6 (right), the second gives 3 (left).3-6 = -3; -3 is pushed. In the opposite order the result would be 3. - The
*operator. The first pop gives -3 (right), the second gives 6 (left).6*(-3) = -18; -18 is pushed. - The expression has ended. One number is left on the stack: the result is -18.
int evaluatePostfix(const char* expr) { int stack[strlen(expr) + 1]; // number stack int top = -1; for (int i = 0; expr[i] != '\0'; i++) { char c = expr[i]; if (c == ' ') continue; if (c >= '0' && c <= '9') { stack[++top] = c - '0'; // operand: push } else { int right = stack[top--]; // first pop: right operand int left = stack[top--]; // second pop: left operand int result; if (c == '+') result = left + right; else if (c == '-') result = left - right; else if (c == '*') result = left * right; else result = left / right; // truncates toward zero stack[++top] = result; // result: push } } return stack[top]; // the one number left is the result}int evaluatePostfix(String expr) { java.util.ArrayDeque<Integer> stack = new java.util.ArrayDeque<>(); // number stack for (int i = 0; i < expr.length(); i++) { char c = expr.charAt(i); if (c == ' ') continue; if (c >= '0' && c <= '9') { stack.push(c - '0'); // operand: push } else { int right = stack.pop(); // first pop: right operand int left = stack.pop(); // second pop: left operand int result; if (c == '+') result = left + right; else if (c == '-') result = left - right; else if (c == '*') result = left * right; else result = left / right; // truncates toward zero stack.push(result); // result: push } } return stack.pop(); // the one number left is the result}def evaluate_postfix(expr): stack = [] # number stack for c in expr: if c == " ": continue if c.isdigit(): stack.append(int(c)) # operand: push else: right = stack.pop() # first pop: right operand left = stack.pop() # second pop: left operand if c == "+": stack.append(left + right) elif c == "-": stack.append(left - right) elif c == "*": stack.append(left * right) else: stack.append(int(left / right)) # truncates toward zero, like C and Java return stack.pop() # the one number left is the resultThe snippets focus on the operation in this lesson. The C examples need stdlib.h.
3Complexity
In the worst case (all digits first, all operators at the end) every digit sits on the stack at the same time.
Postfix has no precedence rules: the order of the operations is already written in the order of the expression. That is why evaluation ends in one pass and never has to look back.
4Common mistake
The most common mistake is mixing up the pop order and treating the first number popped as the left operand:
int left = stack[top--]; // wrong: the first pop is the right operandint right = stack[top--];With addition and multiplication the bug stays hidden, because the order does not change the result. With subtraction and division the result breaks: 82- gives -6 instead of 6, and 6324+-* gives 18 instead of -18. The rule: the first number off the stack is the operand written last, that is, the right one.
5Try it
What is the value of 82/3-?
The answer is A. 8 and 2 are pushed. For / the first pop is 2 (right) and the second is 8 (left): 8/2 = 4. Then 3 is pushed. For - the first pop is 3 (right) and the second is 4 (left): 4-3 = 1.
Show the answer
The answer is A. 8 and 2 are pushed. For / the first pop is 2 (right) and the second is 8 (left): 8/2 = 4. Then 3 is pushed. For - the first pop is 3 (right) and the second is 4 (left): 4-3 = 1.
While evaluating 23*54*+9-, what is the largest number of values on the stack at the same time?
The answer is B. After 2*3 the stack holds 6. Then 5 and 4 are pushed: 6, 5, 4. That is the fullest moment. * leaves 6, 20; + leaves 26; 9 makes it 26, 9; and - leaves 17.
Show the answer
The answer is B. After 2*3 the stack holds 6. Then 5 and 4 are pushed: 6, 5, 4. That is the fullest moment. * leaves 6, 20; + leaves 26; 9 makes it 26, 9; and - leaves 17.
Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.