Kodewick
開始學 →
表示式求值:字尾表示式13 / 50

表示式求值:字尾表示式

第 13 課,共 50 課 · 第 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.c
1#include <stdio.h>2#include <ctype.h>3 4// 只處理一位數:每個字元是一個數或一個運算子5int eval(const char *s) {6    int st[100], top = -1;7    for (int i = 0; s[i] != '\0'; i++) {8        char c = s[i];9        if (isdigit(c)) {10            st[++top] = c - '0';11        } else {12            int b = st[top--];      // 先出來的是右邊的13            int a = st[top--];14            int r = c == '+' ? a + b : c == '-' ? a - b : c == '*' ? a * b : a / b;15            st[++top] = r;16        }17    }18    return st[top];19}20 21int main(void) {22    printf("%d\n", eval("34+2*"));23    printf("%d\n", eval("512+4*+3-"));24    return 0;25}
輸出
14
14

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

猜輸出猜錯也沒關係

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

1#include <stdio.h>2 3int main(void) {4    int st[10], top = -1;5    st[++top] = 9;6    st[++top] = 3;7    int b = st[top--];8    int a = st[top--];9    st[++top] = a - b;10    st[++top] = 2;11    b = st[top--];12    a = st[top--];13    st[++top] = a / b;14    printf("%d\n", st[top]);15    return 0;16}
單選

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

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

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

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

算字尾表示式

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

要顯示
9 6
exercise1.c
1#include <stdio.h>2#include <ctype.h>3 4int eval(const char *s) {5    int st[100], top = -1;6    for (int i = 0; s[i] != '\0'; i++) {7        char c = s[i];8        // 數:push c - '0';運算子:先出 b 再出 a,push a 運算 b9    }10    return st[top];11}12 13int main(void) {14    printf("%d %d\n", eval("52-3*"), eval("62/3+"));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 -

「大於等於」裡的等於很重要:- 遇到堆疊裡的 + 也要先把它 pop 出來,這樣 8 - 3 + 1 才會按從左到右的順序算成 6,而不是 8 − (3 + 1)。

main.c
1#include <stdio.h>2#include <ctype.h>3 4int prio(char op) {5    return (op == '*' || op == '/') ? 2 : (op == '+' || op == '-') ? 1 : 0;   // ( 是 06}7 8void to_postfix(const char *s, char *out) {9    char st[100];10    int top = -1, k = 0;11    for (int i = 0; s[i] != '\0'; i++) {12        char c = s[i];13        if (isdigit(c)) {14            out[k++] = c;15        } else if (c == '(') {16            st[++top] = c;17        } else if (c == ')') {18            while (st[top] != '(')19                out[k++] = st[top--];20            top--;                                // 丟掉 (21        } else {22            while (top >= 0 && prio(st[top]) >= prio(c))23                out[k++] = st[top--];24            st[++top] = c;25        }26    }27    while (top >= 0)28        out[k++] = st[top--];29    out[k] = '\0';30}31 32int main(void) {33    const char *tests[] = {"3+4*2-1", "(1+2)*3-4/2", "8-3+1"};34    char out[100];35    for (int t = 0; t < 3; t++) {36        to_postfix(tests[t], out);37        printf("%-12s -> %s\n", tests[t], out);38    }39    return 0;40}
輸出
3+4*2-1      -> 342*+1-
(1+2)*3-4/2  -> 12+3*42/-
8-3+1        -> 83-1+

( 的優先順序定成 0,正好讓第 4 步「遇到 ( 停」不用單獨寫:任何運算子都比它高,不會把它 pop 出去。

單選

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

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

在空格裡填一個比較符號,讓 8-3+1*2 轉出正確的字尾 83-12*+。

1#include <stdio.h>2#include <ctype.h>3 4int prio(char op) {5    return (op == '*' || op == '/') ? 2 : 1;6}7 8int main(void) {9    const char *s = "8-3+1*2";10    char st[100], out[100];11    int top = -1, k = 0;12    for (int i = 0; s[i] != '\0'; i++) {13        char c = s[i];14        if (isdigit(c)) {15            out[k++] = c;16        } else {17            while (top >= 0 && prio(st[top])  prio(c))18                out[k++] = st[top--];19            st[++top] = c;20        }21    }22    while (top >= 0)23        out[k++] = st[top--];24    out[k] = '\0';25    printf("%s\n", out);26    return 0;27}
練習 2

中綴轉字尾

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

要顯示
123*+4-
exercise2.c
1#include <stdio.h>2#include <ctype.h>3 4int prio(char op) {5    return (op == '*' || op == '/') ? 2 : 1;6}7 8int main(void) {9    const char *s = "1+2*3-4";10    char st[100], out[100];11    int top = -1, k = 0;12    for (int i = 0; s[i] != '\0'; i++) {13        char c = s[i];14        if (isdigit(c)) {15            out[k++] = c;16        } else {17            // 堆疊頂優先順序 >= c 的 pop 到 out,然後 push c18        }19    }20    while (top >= 0)21        out[k++] = st[top--];22    out[k] = '\0';23    printf("%s\n", out);24    return 0;25}
輸出
點「執行」或按 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) 的字首表示式是哪一個?

小結

這一課帶走

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

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