表示式求值:字尾表示式
字尾表示式把運算子寫在兩個數後面,3 4 2 * + 就是 3 + 4 * 2;沒有括號和優先順序,一個堆疊從左到右就能算完,中綴轉字尾也靠一個堆疊。
人寫 3 + 4 * 2,靠的是「先乘除後加減」和括號。程式從左往右讀,讀到 + 時還不知道後面有沒有 *。辦法是換一種寫法:字尾表示式(也叫逆波蘭式),運算子寫在兩個數的後面:3 4 2 * +。它沒有括號、不用管優先順序,一個堆疊就能從左到右算完。
字尾表示式怎麼算
從左往右讀:
- 讀到數:push。
- 讀到運算子:pop 兩次,先出來的是右邊的數 b,後出來的是左邊的數 a,算
a 運算 b,把結果 push 回去。 - 讀完:堆疊裡剩下的那一個就是結果。
top1#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 + * 的值是多少?
+,彈出 3 和 2,push 5,堆疊裡是 6 5;遇到 *,6 × 5 = 30。寫成中綴是 6 * (2 + 3)。15 是把它當成 6 × 2 + 3 算了。讀到 - 時要做三件事。把這三行排好,讓程式算出字尾表示式 8 2 - 的值 6。
int a = st[t--];int b = st[t--];st[++t] = a - b;
6
a - b = 6。前兩行換了位置,a 和 b 就反了,算出來是 2 − 8 = −6。算字尾表示式
✓補全 eval:數 push,運算子 pop 兩次再把結果 push。注意減法和除法裡誰減誰。
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 // 數: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}
中綴怎麼變成字尾
轉換也用一個堆疊,這次堆疊裡放的是運算子:
- 讀到數:直接寫到輸出。
- 讀到
(:push。 - 讀到
):一直 pop 到輸出,直到碰到(;(丟掉。 - 讀到運算子:先把堆疊頂優先順序大於等於它的運算子一個個 pop 到輸出(遇到
(停),再把它 push。 - 讀完:堆疊裡剩下的全部 pop 到輸出。
看 3 + 4 * 2 - 1 一步步怎麼走:
| 讀到 | 做了什麼 | 輸出 | 運算子堆疊 |
|---|---|---|---|
| 3 | 寫到輸出 | 3 | |
| + | 堆疊空,push | 3 | + |
| 4 | 寫到輸出 | 3 4 | + |
| * | 堆疊頂 + 比 * 低,不 pop;push | 3 4 | + * |
| 2 | 寫到輸出 | 3 4 2 | + * |
| - | 堆疊頂 * 高於 -,pop;+ 和 - 一樣高,也 pop;再 push - | 3 4 2 * + | - |
| 1 | 寫到輸出 | 3 4 2 * + 1 | - |
| 讀完 | 全部 pop | 3 4 2 * + 1 - |
運算子堆疊
+*-「大於等於」裡的等於很重要:- 遇到堆疊裡的 + 也要先把它 pop 出來,這樣 8 - 3 + 1 才會按從左到右的順序算成 6,而不是 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; // ( 是 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 轉成字尾是什麼?
( push;3 輸出;+ push;4 輸出;) 把 + pop 到輸出,丟掉 (;* push;2 輸出;讀完 pop *。括號裡的先算,所以 3 4 + 先寫出來。在空格裡填一個比較符號,讓 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}
+ 時先把 - 送到輸出,8 - 3 才會先算,從左往右。* 比 + 高,不 pop +,直接 push。中綴轉字尾
✓補全運算子那一支:先把堆疊頂優先順序大於等於它的都 pop 到輸出,再 push 它。這裡沒有括號,堆疊用 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 // 堆疊頂優先順序 >= 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}
考試手算:加括號法
考試裡常常只讓你寫出結果,不用一步步走堆疊。這時有個快辦法,分三步:
- 按運算的先後,給每一步加上括號:
3 + 4 * 2 - 1寫成((3 + (4 * 2)) - 1)。 - 把每個運算子挪到它那對括號的右括號後面。
- 去掉所有括號:
3 4 2 * + 1 -。
把運算子挪到左括號前面,得到的就是字首表示式(波蘭式):- + 3 * 4 2 1。數的先後順序始終不變,變的只是運算子的位置,這一點可以用來快速排除錯的選項。
a * b + c / d 的字尾表示式是哪一個?
((a * b) + (c / d))。運算子挪到右括號後面:a b *、c d /,最後是 +,連起來是 a b * c d / +。字母的順序一直是 a b c d。a + b * (c - d) 的字首表示式是哪一個?
(a + (b * (c - d)))。每個運算子挪到它的左括號前面:+ a * b - c d。a b c d - * + 是字尾寫法。用 STL 寫
真的表示式裡數不止一位。用空格分開每一項,數字一位位讀出來拼成整數,堆疊換成 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--; // 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}
/:先出來的 4 是 b,20 是 a,20 / 4 = 5,push;3 入堆疊;-:b = 3,a = 5,5 − 3 = 2。最後堆疊裡只剩這一個結果,size 是 1。小結
表示式求值:先轉字尾,再用堆疊算
- 求值:數 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(); }