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--];