Kodewick
開始學 →
表示式求值:字尾表示式15 / 52

表示式求值:字尾表示式

第 15 課,共 52 課 · 第 3 部分 · 堆疊和佇列 · 約 15 分鐘

字尾表示式把運算子寫在兩個數後面,3 4 2 * + 就是 3 + 4 * 2;沒有括號和優先順序,一個堆疊從左到右就能算完,中綴轉字尾也靠一個堆疊。

人寫 3 + 4 * 2,靠的是「先乘除後加減」和括號。程式從左往右讀,讀到 + 時還不知道後面有沒有 *。辦法是換一種寫法:字尾表示式(也叫逆波蘭式),運算子寫在兩個數的後面:3 4 2 * +。它沒有括號、不用管優先順序,一個堆疊就能從左到右算完。

字尾表示式怎麼算

從左往右讀:

  • 讀到數:push。
  • 讀到運算子:pop 兩次,先出來的是右邊的數 b,後出來的是左邊的數 a,算 a 運算 b,把結果 push 回去。
  • 讀完:堆疊裡剩下的那一個就是結果。
堆疊(堆疊底在左)012

算 3 4 + 2 *:遇到運算子就從堆疊頂拿兩個數,算完放回去
main.cpp
1#include <iostream>2#include <string>3using namespace std;4 5// 只處理一位數:每個字元是一個數或一個運算子6int 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--];      // 先出來的是右邊的13            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

第二個是 5 + (1 + 2) * 4 - 3,寫成字尾是 5 1 2 + 4 * + 3 -,結果也是 14。

猜輸出猜錯也沒關係

這是在算字尾表示式 9 3 - 2 /,印出幾?

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}
單選

字尾表示式 6 2 3 + * 的值是多少?

排順序拖動或點箭頭排順序

讀到 - 時要做三件事。把這三行排好,讓程式算出字尾表示式 8 2 - 的值 6。

  1. int a = st[t--];
  2. int b = st[t--];
  3. st[++t] = a - b;
要顯示
6
練習 1

算字尾表示式

補全 eval:數 push,運算子 pop 兩次再把結果 push。注意減法和除法裡誰減誰。

要顯示
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        // 數:push c - '0';運算子:先出 b 再出 a,push a 運算 b9    }10    return st[t];11}12 13int main() {14    cout << eval("52-3*") << " " << eval("62/3+") << "\n";15    return 0;16}
輸出
點「執行」或按 Ctrl+Enter

中綴怎麼變成字尾

轉換也用一個堆疊,這次堆疊裡放的是運算子:

  1. 讀到數:直接寫到輸出。
  2. 讀到 (:push。
  3. 讀到 ):一直 pop 到輸出,直到碰到 (;( 丟掉。
  4. 讀到運算子:先把堆疊頂優先順序大於等於它的運算子一個個 pop 到輸出(遇到 ( 停),再把它 push。
  5. 讀完:堆疊裡剩下的全部 pop 到輸出。

看 3 + 4 * 2 - 1 一步步怎麼走:

讀到做了什麼輸出運算子堆疊
3寫到輸出3
+堆疊空,push3+
4寫到輸出3 4+
*堆疊頂 + 比 * 低,不 pop;push3 4+ *
2寫到輸出3 4 2+ *
-堆疊頂 * 高於 -,pop;+ 和 - 一樣高,也 pop;再 push -3 4 2 * +-
1寫到輸出3 4 2 * + 1-
讀完全部 pop3 4 2 * + 1 -

運算子堆疊

3 + 4 * 2 - 1 轉字尾時的運算子堆疊:數直接輸出,只有運算子進堆疊

「大於等於」裡的等於很重要:- 遇到堆疊裡的 + 也要先把它 pop 出來,這樣 8 - 3 + 1 才會按從左到右的順序算成 6,而不是 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;   // ( 是 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--;                                  // 丟掉 (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+

( 的優先順序定成 0,正好讓第 4 步「遇到 ( 停」不用單獨寫:任何運算子都比它高,不會把它 pop 出去。輸出用 string 的 += 一個個接上,不用自己管下標和結尾的 '\0'。

單選

中綴 (3 + 4) * 2 轉成字尾是什麼?

填空點一個填進空格,再點空格可以拿回來

在空格裡填一個比較符號,讓 8-3+1*2 轉出正確的字尾 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}
練習 2

中綴轉字尾

補全運算子那一支:先把堆疊頂優先順序大於等於它的都 pop 到輸出,再 push 它。這裡沒有括號,堆疊用 stack<char>。

要顯示
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            // 堆疊頂優先順序 >= c 的 pop 到 out,然後 push c19        }20    }21    while (!st.empty()) {22        out += st.top();23        st.pop();24    }25    cout << out << "\n";26    return 0;27}
輸出
點「執行」或按 Ctrl+Enter

考試手算:加括號法

考試裡常常只讓你寫出結果,不用一步步走堆疊。這時有個快辦法,分三步:

  1. 按運算的先後,給每一步加上括號:3 + 4 * 2 - 1 寫成 ((3 + (4 * 2)) - 1)。
  2. 把每個運算子挪到它那對括號的右括號後面。
  3. 去掉所有括號:3 4 2 * + 1 -。

把運算子挪到左括號前面,得到的就是字首表示式(波蘭式):- + 3 * 4 2 1。數的先後順序始終不變,變的只是運算子的位置,這一點可以用來快速排除錯的選項。

單選

a * b + c / d 的字尾表示式是哪一個?

單選

a + b * (c - d) 的字首表示式是哪一個?

用 STL 寫

真的表示式裡數不止一位。用空格分開每一項,數字一位位讀出來拼成整數,堆疊換成 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--;                          // for 還會再加 120            st.push(x);21        } else {22            int b = st.top(); st.pop();   // 先出來的是右邊的23            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

因為 pop() 不回傳值,取一個數要寫兩句:int b = st.top(); st.pop();。每一項 push 一次、最多 pop 一次,stack<int> 的這些操作都是 O(1),整個表示式 O(n)。

步驟堆疊裡放用的 STL代價
中綴轉字尾運算子stack<char>(或 string 當堆疊)O(n)
字尾求值數stack<int>O(n)

面試裡: 「逆波蘭表示式求值」直接就是上面的 eval,題目給的是 vector<string>,用 stoi 把每一項變成數。「基本計算器」帶括號和加減,常見寫法是兩個堆疊(數一個、運算子一個),邊讀邊算,規則就是這一課的轉換規則。

猜輸出猜錯也沒關係

這段程式用 stack<int> 算字尾表示式 20 4 / 3 -,印出什麼?

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}

小結

這一課帶走

表示式求值:先轉字尾,再用堆疊算

  • 求值:數 push;運算子 pop 出 b、再 pop 出 a,push a 運算 b
  • 轉換:數直接輸出;運算子先把堆疊頂優先順序 ≥ 它的 pop 出去再 push
  • ( push;) 一直 pop 到 (;讀完全部 pop
  • stack 的 pop 不回傳值:先 top() 再 pop()
1int b = st.top(); st.pop();2int a = st.top(); st.pop();3st.push(a - b);   // 後出的減先出的4while (!ops.empty() && prio(ops.top()) >= prio(c))5    { out += ops.top(); ops.pop(); }