Kodewick
Start learning →
Evaluating expressions: postfix15 / 52

Evaluating expressions: postfix

Lesson 15 of 52 · Part 3 · Stacks and queues · about 15 minutes

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 b and push the result.
  • At the end: the one value left on the stack is the answer.
stack (bottom on the left)012

Evaluating 3 4 + 2 *: at an operator, take two numbers off the top and put the result back
main.cpp
1#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}
Output
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.

Guess the outputA wrong guess is fine

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}
Choose one

What is the value of the postfix expression 6 2 3 + *?

Put in orderDrag, or use the arrows

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.

  1. int a = st[t--];
  2. int b = st[t--];
  3. st[++t] = a - b;
Should print
6
Exercise 1

Evaluate postfix

Fill in eval: push a number; at an operator pop twice and push the result. Mind which one is subtracted from which.

It should print
9 6
exercise1.cpp
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}
Output
Press Run or Ctrl+Enter

Turning infix into postfix

The conversion uses a stack too, this time holding operators:

  1. A number: write it straight to the output.
  2. (: push it.
  3. ): pop to the output until you reach (; throw the ( away.
  4. 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.
  5. At the end: pop everything left to the output.

Here is 3 + 4 * 2 - 1 step by step:

ReadWhat happensOutputOperator stack
3To the output3
+Stack empty, push3+
4To the output3 4+
*The top + is lower than *, no pop; push3 4+ *
2To the output3 4 2+ *
-The top * is higher than -, pop; + is as high as -, pop it too; then push -3 4 2 * +-
1To the output3 4 2 * + 1-
EndPop everything3 4 2 * + 1 -

operator stack

The operator stack while 3 + 4 * 2 - 1 becomes postfix: numbers go straight out, only operators go on the 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).

main.cpp
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}
Output
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.

Choose one

What is the infix (3 + 4) * 2 in postfix?

Fill inTap one to fill a blank; tap a blank to take it back

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}
Exercise 2

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>.

It should print
123*+4-
exercise2.cpp
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}
Output
Press Run or Ctrl+Enter

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:

  1. Put brackets round every step, in the order it is worked out: 3 + 4 * 2 - 1 becomes ((3 + (4 * 2)) - 1).
  2. Move each operator just past its closing bracket.
  3. 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.

Choose one

Which is the postfix form of a * b + c / d?

Choose one

Which is the prefix form of a + b * (c - d)?

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>:

main.cpp
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}
Output
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).

StepThe stack holdsSTLCost
Infix to postfixOperatorsstack<char> (or a string as a stack)O(n)
Evaluating postfixNumbersstack<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.

Guess the outputA wrong guess is fine

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}

Summary

Take-away

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(); }