Evaluating expressions: postfix
A postfix expression puts each operator after its two numbers, so 3 4 2 * + means 3 + 4 * 2; with no parentheses or precedence, one stack evaluates it left to right, and a stack also turns infix into postfix.
People write 3 + 4 * 2 and rely on "multiply and divide before add and subtract", plus parentheses. A program reading left to right doesn't know, when it reaches +, whether a * is coming. The way out is a different notation: postfix (also called reverse Polish notation), with the operator written after its two numbers: 3 4 2 * +. It has no parentheses and no precedence to worry about, and one stack evaluates it left to right.
Evaluating postfix
Read from left to right:
- A number: push it.
- An operator: pop twice. The first one out is the right-hand number b, the second is the left-hand number a. Work out
a op band push the result. - At the end: the one value left on the stack is the answer.
top1#include <iostream>2#include <string>3using namespace std;4 5// single digits only: each character is a number or an operator6int eval(const string& s) {7 int st[100], t = -1;8 for (char c : s) {9 if (c >= '0' && c <= '9') {10 st[++t] = c - '0';11 } else {12 int b = st[t--]; // the first one out is the right-hand one13 int a = st[t--];14 int r = c == '+' ? a + b : c == '-' ? a - b : c == '*' ? a * b : a / b;15 st[++t] = r;16 }17 }18 return st[t];19}20 21int main() {22 cout << eval("34+2*") << "\n";23 cout << eval("512+4*+3-") << "\n";24 return 0;25}
14 14
The second one is 5 + (1 + 2) * 4 - 3, which in postfix is 5 1 2 + 4 * + 3 -; it also comes to 14.
This evaluates the postfix expression 9 3 - 2 /. What does it print?
1#include <iostream>2using namespace std;3 4int main() {5 int st[10], t = -1;6 st[++t] = 9;7 st[++t] = 3;8 int b = st[t--];9 int a = st[t--];10 st[++t] = a - b;11 st[++t] = 2;12 b = st[t--];13 a = st[t--];14 st[++t] = a / b;15 cout << st[t] << "\n";16 return 0;17}
What is the value of the postfix expression 6 2 3 + *?
+, 3 and 2 come off and 5 goes on, leaving 6 5; at *, 6 × 5 = 30. In infix it is 6 * (2 + 3). 15 is what you get by reading it as 6 × 2 + 3.When the program reads -, it does three things. Put these three lines in order so it works out the postfix expression 8 2 - and prints 6.
int a = st[t--];int b = st[t--];st[++t] = a - b;
6
a - b = 6 is pushed. Swap the first two lines and a and b trade places, giving 2 − 8 = −6.Evaluate postfix
✓Fill in eval: push a number; at an operator pop twice and push the result. Mind which one is subtracted from which.
9 6
1#include <iostream>2#include <string>3using namespace std;4 5int eval(const string& s) {6 int st[100], t = -1;7 for (char c : s) {8 // number: push c - '0'; operator: b out first, then a, push a op b9 }10 return st[t];11}12 13int main() {14 cout << eval("52-3*") << " " << eval("62/3+") << "\n";15 return 0;16}
Turning infix into postfix
The conversion uses a stack too, this time holding operators:
- A number: write it straight to the output.
(: push it.): pop to the output until you reach(; throw the(away.- An operator: first pop to the output every operator on top whose precedence is greater than or equal to its own (stop at
(), then push it. - At the end: pop everything left to the output.
Here is 3 + 4 * 2 - 1 step by step:
| Read | What happens | Output | Operator stack |
|---|---|---|---|
| 3 | To the output | 3 | |
| + | Stack empty, push | 3 | + |
| 4 | To the output | 3 4 | + |
| * | The top + is lower than *, no pop; push | 3 4 | + * |
| 2 | To the output | 3 4 2 | + * |
| - | The top * is higher than -, pop; + is as high as -, pop it too; then push - | 3 4 2 * + | - |
| 1 | To the output | 3 4 2 * + 1 | - |
| End | Pop everything | 3 4 2 * + 1 - |
operator stack
+*-The equal in "greater than or equal" matters: a - that meets a + on the stack must pop it first, so that 8 - 3 + 1 is worked out left to right as 6, not 8 − (3 + 1).
1#include <iostream>2#include <string>3using namespace std;4 5int prio(char op) {6 return (op == '*' || op == '/') ? 2 : (op == '+' || op == '-') ? 1 : 0; // ( is 07}8 9string toPostfix(const string& s) {10 char st[100];11 int t = -1;12 string out;13 for (char c : s) {14 if (c >= '0' && c <= '9') {15 out += c;16 } else if (c == '(') {17 st[++t] = c;18 } else if (c == ')') {19 while (st[t] != '(')20 out += st[t--];21 t--; // throw away the (22 } else {23 while (t >= 0 && prio(st[t]) >= prio(c))24 out += st[t--];25 st[++t] = c;26 }27 }28 while (t >= 0)29 out += st[t--];30 return out;31}32 33int main() {34 string tests[] = {"3+4*2-1", "(1+2)*3-4/2", "8-3+1"};35 for (const string& s : tests)36 cout << s << string(12 - s.size(), ' ') << " -> " << toPostfix(s) << "\n";37 return 0;38}
3+4*2-1 -> 342*+1- (1+2)*3-4/2 -> 12+3*42/- 8-3+1 -> 83-1+
Giving ( precedence 0 means step 4's "stop at (" needs no code of its own: every operator is higher, so none of them pops it. The output is built with string's +=, one character at a time, with no index or closing '\0' to manage.
What is the infix (3 + 4) * 2 in postfix?
( is pushed; 3 goes to the output; + is pushed; 4 goes out; ) pops + to the output and throws away (; * is pushed; 2 goes out; at the end * is popped. What's in the brackets comes first, so 3 4 + is written first.Fill in the comparison so that 8-3+1*2 comes out as the right postfix, 83-12*+.
1#include <iostream>2#include <string>3using namespace std;4 5int prio(char op) {6 return (op == '*' || op == '/') ? 2 : 1;7}8 9int main() {10 string s = "8-3+1*2";11 char st[100];12 int t = -1;13 string out;14 for (char c : s) {15 if (c >= '0' && c <= '9') {16 out += c;17 } else {18 while (t >= 0 && prio(st[t]) prio(c))19 out += st[t--];20 st[++t] = c;21 }22 }23 while (t >= 0)24 out += st[t--];25 cout << out << "\n";26 return 0;27}
+ first sends - to the output, so 8 - 3 is done first, left to right. * is higher than +, so + stays and * is pushed.Infix to postfix
✓Fill in the operator branch: first pop to the output every operator on top with precedence greater than or equal to it, then push it. No parentheses here; the stack is a stack<char>.
123*+4-
1#include <iostream>2#include <stack>3#include <string>4using namespace std;5 6int prio(char op) {7 return (op == '*' || op == '/') ? 2 : 1;8}9 10int main() {11 string s = "1+2*3-4";12 stack<char> st;13 string out;14 for (char c : s) {15 if (c >= '0' && c <= '9') {16 out += c;17 } else {18 // pop the tops with precedence >= c to out, then push c19 }20 }21 while (!st.empty()) {22 out += st.top();23 st.pop();24 }25 cout << out << "\n";26 return 0;27}
Converting by hand in exams: the bracket trick
Exam questions often just want the answer, not every step on the stack. There's a quick way, in three steps:
- Put brackets round every step, in the order it is worked out:
3 + 4 * 2 - 1becomes((3 + (4 * 2)) - 1). - Move each operator just past its closing bracket.
- Drop all the brackets:
3 4 2 * + 1 -.
Move each operator just before its opening bracket instead and you get the prefix expression (Polish notation): - + 3 * 4 2 1. The numbers never change order, only the operators move, which is a quick way to rule out wrong answers.
Which is the postfix form of a * b + c / d?
((a * b) + (c / d)). Each operator goes past its closing bracket: a b *, c d /, and + last, so a b * c d / +. The letters stay in the order a b c d.Which is the prefix form of a + b * (c - d)?
(a + (b * (c - d))). Each operator moves in front of its opening bracket: + a * b - c d. a b c d - * + is the postfix form.With the STL
Real expressions have numbers with more than one digit. Separate the items with spaces, read the digits one by one into an integer, and use a stack<int>:
1#include <iostream>2#include <stack>3#include <string>4using namespace std;5 6int apply(int a, char op, int b) {7 return op == '+' ? a + b : op == '-' ? a - b : op == '*' ? a * b : a / b;8}9 10int eval(const string& s) {11 stack<int> st;12 for (size_t i = 0; i < s.size(); i++) {13 char c = s[i];14 if (c == ' ') continue;15 if (c >= '0' && c <= '9') {16 int x = 0;17 while (i < s.size() && s[i] >= '0' && s[i] <= '9')18 x = x * 10 + (s[i++] - '0');19 i--; // the for adds 1 again20 st.push(x);21 } else {22 int b = st.top(); st.pop(); // the first one out is the right-hand one23 int a = st.top(); st.pop();24 st.push(apply(a, c, b));25 }26 }27 return st.top();28}29 30int main() {31 cout << eval("100 20 3 * -") << "\n";32 cout << eval("15 7 1 1 + - / 3 * 2 1 1 + + -") << "\n";33 return 0;34}
40 5
Since pop() returns nothing, taking a number off takes two statements: int b = st.top(); st.pop();. Each item is pushed once and popped at most once, and these stack<int> operations are all O(1), so the whole expression is O(n).
| Step | The stack holds | STL | Cost |
|---|---|---|---|
| Infix to postfix | Operators | stack<char> (or a string as a stack) | O(n) |
| Evaluating postfix | Numbers | stack<int> | O(n) |
In interviews: "Evaluate reverse Polish notation" is the eval above, except the input is a vector<string> and stoi turns each item into a number. "Basic calculator" with parentheses and + − is usually written with two stacks (one for numbers, one for operators), working things out as it reads, by this lesson's conversion rule.
This program works out the postfix expression 20 4 / 3 - with stack<int>. What does it print?
1#include <iostream>2#include <stack>3using namespace std;4 5int main() {6 stack<int> st;7 st.push(20);8 st.push(4);9 int b = st.top(); st.pop();10 int a = st.top(); st.pop();11 st.push(a / b);12 st.push(3);13 b = st.top(); st.pop();14 a = st.top(); st.pop();15 st.push(a - b);16 cout << st.top() << " " << st.size() << "\n";17 return 0;18}
/: the 4 popped first is b, 20 is a, 20 / 4 = 5, pushed; 3 is pushed; -: b = 3, a = 5, 5 − 3 = 2. At the end only that result is left, so size is 1.Summary
Evaluating expressions: convert to postfix, then use a stack
- Evaluate: push numbers; at an operator pop b, then a, and push a op b
- Convert: numbers go straight out; an operator first pops the tops with precedence ≥ its own, then is pushed
- ( is pushed; ) pops until (; at the end pop everything
- stack's pop returns nothing: top() first, then pop()
1int b = st.top(); st.pop();2int a = st.top(); st.pop();3st.push(a - b); // second out minus first out4while (!ops.empty() && prio(ops.top()) >= prio(c))5 { out += ops.top(); ops.pop(); }