---
title: 数据结构与算法基础（青岛大学-王卓）
author: 萑澈
pubDatetime: 2026-11-09T00:00:00Z
featured: false
draft: false
printable: true
tags:
  - 数据结构
  - cs408
  - 考研
  - 王卓
  - 青岛大学
description: "王卓《数据结构与算法基础（青岛大学）》全课程总结：绪论、线性表、栈和队列、串/数组/广义表、树与二叉树、图、查找、排序。视频：https://www.bilibili.com/video/BV1nJ411V7bd/"
---

## 第1章 绪论

### 数据结构研究的内容

用计算机解决问题的一般过程：从问题中抽象出数学模型 → 针对模型设计算法 → 用某种语言编写程序并上机调试。

- **数值计算问题**：模型是数学方程（线性方程组、微分方程），操作对象是数值，研究重点是计算方法。计算机擅长快速、复杂的计算。
- **非数值计算问题**：操作对象是字符、表格、图像、声音等，模型不再是方程，而是**表、树、图**这类具有逻辑关系的数据；典型操作是增、删、查、改，而非算术运算。

| 问题 | 操作对象 | 对象间关系 | 抽象出的结构 |
| --- | --- | --- | --- |
| 学生/图书/人事/仓库/通讯录管理 | 记录 | 一对一的前后次序 | 线性表 |
| 人机对弈（井字棋派生格局） | 棋局格局 | 一对多 | 树 |
| 磁盘文件目录 | 目录 | 一对多 | 树 |
| 地图导航求最短路径 | 地点与道路 | 多对多 | 图 |

结论：数据结构研究非数值计算程序设计中的**操作对象、对象之间的关系，以及施加于其上的操作**。

> **★考点**：数值计算与非数值计算的数学模型差异——前者是方程，后者是表/树/图。

### 数据、数据元素、数据项与数据对象

- **数据**：能够输入计算机且能被计算机识别、存储和加工的各种符号的集合，是信息的载体。分为数值型数据与非数值型数据。
- **数据元素**：数据中关系紧密、在程序中通常作为一个整体进行处理的基本单位。也称元素、记录、结点、顶点（对弈中的格局称结点，导航中的地点称顶点）。
- **数据项**：构成数据元素、不可分割的最小单位（如学号、姓名、性别）。
- **数据对象**：性质相同的数据元素的集合，是数据的子集（如整数集合、大写字母集合）。

层次关系：数据（集合）⊇ 数据对象（子集）；数据元素由若干数据项组成。

> **注意**：数据元素是“个体/基本单位”，数据对象是“同类个体的集合”，二者是元素与集合的关系，不是同一层次的概念。

### 逻辑结构及其分类

**结构**即数据元素之间的相互关系。**数据结构**是相互之间存在一种或多种特定关系的数据元素的集合，也称带结构的数据元素的集合。它包含三方面内容：

1. 数据元素之间的**逻辑关系**——逻辑结构；
2. 数据元素及其关系在计算机存储器中的表示——**存储结构**（物理结构）；
3. 对数据元素可施加的操作及操作在相应存储结构上的实现——**数据的运算**。

逻辑结构从具体问题中抽象得到，**与如何存储无关**。两种划分方法：

| 划分 | 类别 | 关系特征 |
| --- | --- | --- |
| 二分 | 线性结构 | 一对一；仅一个开始结点、一个终端结点，其余最多一个直接前驱和一个直接后继 |
| | 非线性结构 | 一对多或多对多 |
| 四分 | 集合结构 | 元素同属一个集合，别无其他关系 |
| | 线性结构 | 一对一 |
| | 树形结构 | 一对多的层次关系 |
| | 图状结构 | 多对多的任意关系 |

> **注意**：线性结构要求“最多一个前驱、最多一个后继”且首尾各一；环状、一对多、多对多都不满足。

<figure class="cpd-figure not-content" id="wz-w1-fig-1">
  <svg viewBox="0 0 680 310" role="img" aria-label="数据概念四层关系与四类基本逻辑结构对比">
    <defs>
      <marker id="wz-w1-arr-0" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="18" y="14" width="644" height="108" rx="6"/>
    <line class="fig-line-accent" x1="158" y1="68" x2="188" y2="68" marker-end="url(#wz-w1-arr-0)"/>
    <line class="fig-line-accent" x1="342" y1="68" x2="372" y2="68" marker-end="url(#wz-w1-arr-0)"/>
    <rect class="fig-box-blue" x="30" y="42" width="126" height="52" rx="5"/>
    <rect class="fig-box-accent" x="192" y="42" width="148" height="52" rx="5"/>
    <rect class="fig-box" x="376" y="42" width="272" height="52" rx="5"/>
    <line class="fig-divider" x1="466" y1="42" x2="466" y2="94"/>
    <line class="fig-divider" x1="556" y1="42" x2="556" y2="94"/>
    <text class="fig-title" x="30" y="32" font-size="12.5">数据概念层次：数据 ⊇ 数据对象（同类集合） ⊇ 数据元素（基本个体） ⊇ 数据项（最小单位）</text>
    <text class="fig-blue" x="93" y="64" text-anchor="middle" font-size="12">数据对象</text>
    <text class="fig-muted" x="93" y="82" text-anchor="middle" font-size="11">学生信息表集合</text>
    <text class="fig-accent" x="266" y="64" text-anchor="middle" font-size="12">数据元素（记录）</text>
    <text class="fig-muted" x="266" y="82" text-anchor="middle" font-size="11">1 名学生的完整记录</text>
    <text class="fig-label" x="421" y="64" text-anchor="middle" font-size="11.5">学号: 101</text>
    <text class="fig-muted" x="421" y="82" text-anchor="middle" font-size="10.5">数据项 1</text>
    <text class="fig-label" x="511" y="64" text-anchor="middle" font-size="11.5">姓名: 张三</text>
    <text class="fig-muted" x="511" y="82" text-anchor="middle" font-size="10.5">数据项 2</text>
    <text class="fig-label" x="602" y="64" text-anchor="middle" font-size="11.5">成绩: 92</text>
    <text class="fig-muted" x="602" y="82" text-anchor="middle" font-size="10.5">数据项 3</text>
    <rect class="fig-box-subtle" x="18" y="136" width="150" height="158" rx="6"/>
    <rect class="fig-box-subtle" x="182" y="136" width="150" height="158" rx="6"/>
    <rect class="fig-box-subtle" x="346" y="136" width="150" height="158" rx="6"/>
    <rect class="fig-box-subtle" x="510" y="136" width="152" height="158" rx="6"/>
    <ellipse class="fig-box-dashed" cx="93" cy="214" rx="54" ry="38"/>
    <line class="fig-line-accent" x1="210" y1="214" x2="241" y2="214" marker-end="url(#wz-w1-arr-0)"/>
    <line class="fig-line-accent" x1="271" y1="214" x2="302" y2="214" marker-end="url(#wz-w1-arr-0)"/>
    <line class="fig-line" x1="421" y1="186" x2="386" y2="232"/>
    <line class="fig-line" x1="421" y1="186" x2="421" y2="232"/>
    <line class="fig-line" x1="421" y1="186" x2="456" y2="232"/>
    <line class="fig-line" x1="556" y1="190" x2="616" y2="190"/>
    <line class="fig-line" x1="556" y1="190" x2="556" y2="240"/>
    <line class="fig-line" x1="616" y1="190" x2="616" y2="240"/>
    <line class="fig-line" x1="556" y1="240" x2="616" y2="240"/>
    <line class="fig-line" x1="556" y1="190" x2="616" y2="240"/>
    <circle class="fig-box" cx="72" cy="202" r="11"/>
    <circle class="fig-box" cx="112" cy="198" r="11"/>
    <circle class="fig-box" cx="84" cy="230" r="11"/>
    <circle class="fig-box" cx="116" cy="228" r="11"/>
    <circle class="fig-box-accent" cx="198" cy="214" r="12"/>
    <circle class="fig-box-accent" cx="257" cy="214" r="12"/>
    <circle class="fig-box-accent" cx="316" cy="214" r="12"/>
    <circle class="fig-box-green" cx="421" cy="186" r="12"/>
    <circle class="fig-box" cx="386" cy="236" r="11"/>
    <circle class="fig-box" cx="421" cy="236" r="11"/>
    <circle class="fig-box" cx="456" cy="236" r="11"/>
    <circle class="fig-box-purple" cx="556" cy="190" r="11"/>
    <circle class="fig-box-purple" cx="616" cy="190" r="11"/>
    <circle class="fig-box-purple" cx="556" cy="240" r="11"/>
    <circle class="fig-box-purple" cx="616" cy="240" r="11"/>
    <text class="fig-title" x="93" y="158" text-anchor="middle" font-size="12.5">① 集合结构</text>
    <text class="fig-muted" x="93" y="278" text-anchor="middle" font-size="11">同属一集，无其他关系</text>
    <text class="fig-title" x="257" y="158" text-anchor="middle" font-size="12.5">② 线性结构（1:1）</text>
    <text class="fig-muted" x="257" y="278" text-anchor="middle" font-size="11">唯一首尾，前驱后继各一</text>
    <text class="fig-title" x="421" y="158" text-anchor="middle" font-size="12.5">③ 树形结构（1:N）</text>
    <text class="fig-muted" x="421" y="278" text-anchor="middle" font-size="11">层次分支，双亲唯一</text>
    <text class="fig-title" x="586" y="158" text-anchor="middle" font-size="12.5">④ 图状结构（M:N）</text>
    <text class="fig-muted" x="586" y="278" text-anchor="middle" font-size="11">任意互连，多前驱多后继</text>
  </svg>
  <figcaption>数据四层概念体系与四类基本逻辑结构（逻辑结构独立于计算机存储方式）</figcaption>
</figure>

### 存储结构及其分类

**存储结构**是逻辑结构在存储器中的表示，既要存元素本身，也要存元素之间的关系。

- **顺序存储**：用一片**连续**的存储单元，按逻辑次序依次存放，以存储单元的先后位置表示前驱后继关系。逻辑上相邻 ⇒ 物理上也相邻。
- **链式存储**：用任意（可不连续）存储单元，每个结点除元素本身外还存**后继的地址（指针）**，靠指针把元素链接起来。
- **索引存储**：存储信息的同时建立索引表（如通讯录按拼音首字母建索引），查找时先查索引再取数据。
- **散列存储**：由数据元素的**关键字直接计算**出存储位置。

<figure class="cpd-figure not-content" id="wz-fig-1">
  <svg viewBox="0 0 680 326" role="img" aria-label="四种基本存储结构对比：顺序存储、链式存储、索引存储与散列存储">
    <defs>
      <marker id="wz-w1-arr-1" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="18" y="14" width="644" height="82" rx="6"/>
    <rect class="fig-box" x="32" y="40" width="84" height="34"/>
    <rect class="fig-box" x="116" y="40" width="84" height="34"/>
    <rect class="fig-box" x="200" y="40" width="84" height="34"/>
    <rect class="fig-box" x="284" y="40" width="84" height="34"/>
    <rect class="fig-box-green" x="394" y="40" width="250" height="34" rx="5"/>
    <text class="fig-title" x="32" y="31" font-size="12.5">① 顺序存储：连续存储单元，逻辑相邻 ⇔ 物理相邻</text>
    <text class="fig-label" x="74" y="61" text-anchor="middle" font-size="12.5">a₁</text>
    <text class="fig-label" x="158" y="61" text-anchor="middle" font-size="12.5">a₂</text>
    <text class="fig-label" x="242" y="61" text-anchor="middle" font-size="12.5">a₃</text>
    <text class="fig-label" x="326" y="61" text-anchor="middle" font-size="12.5">a₄</text>
    <text class="fig-muted" x="74" y="88" text-anchor="middle" font-size="11">2000</text>
    <text class="fig-muted" x="158" y="88" text-anchor="middle" font-size="11">2008</text>
    <text class="fig-muted" x="242" y="88" text-anchor="middle" font-size="11">2016</text>
    <text class="fig-muted" x="326" y="88" text-anchor="middle" font-size="11">2024</text>
    <text class="fig-green" x="519" y="61" text-anchor="middle" font-size="11.5">地址连续 · 随机存取 O(1) · 存储密度 = 1</text>
    <rect class="fig-box-subtle" x="18" y="106" width="644" height="90" rx="6"/>
    <line class="fig-line-accent" x1="136" y1="152" x2="178" y2="152" marker-end="url(#wz-w1-arr-1)"/>
    <line class="fig-line-accent" x1="286" y1="152" x2="328" y2="152" marker-end="url(#wz-w1-arr-1)"/>
    <line class="fig-line-accent" x1="436" y1="152" x2="478" y2="152" marker-end="url(#wz-w1-arr-1)"/>
    <rect class="fig-box" x="32" y="134" width="104" height="36" rx="4"/>
    <rect class="fig-box" x="182" y="134" width="104" height="36" rx="4"/>
    <rect class="fig-box" x="332" y="134" width="104" height="36" rx="4"/>
    <rect class="fig-box" x="482" y="134" width="104" height="36" rx="4"/>
    <line class="fig-divider" x1="86" y1="134" x2="86" y2="170"/>
    <line class="fig-divider" x1="236" y1="134" x2="236" y2="170"/>
    <line class="fig-divider" x1="386" y1="134" x2="386" y2="170"/>
    <line class="fig-divider" x1="536" y1="134" x2="536" y2="170"/>
    <text class="fig-title" x="32" y="124" font-size="12.5">② 链式存储：任意离散单元 + 指针域显式存放后继地址</text>
    <text class="fig-label" x="59" y="156" text-anchor="middle" font-size="12.5">a₁</text>
    <text class="fig-blue" x="111" y="156" text-anchor="middle" font-size="11.5">130</text>
    <text class="fig-label" x="209" y="156" text-anchor="middle" font-size="12.5">a₂</text>
    <text class="fig-blue" x="261" y="156" text-anchor="middle" font-size="11.5">135</text>
    <text class="fig-label" x="359" y="156" text-anchor="middle" font-size="12.5">a₃</text>
    <text class="fig-blue" x="411" y="156" text-anchor="middle" font-size="11.5">170</text>
    <text class="fig-label" x="509" y="156" text-anchor="middle" font-size="12.5">a₄</text>
    <text class="fig-muted" x="561" y="156" text-anchor="middle" font-size="12">∧</text>
    <text class="fig-muted" x="84" y="186" text-anchor="middle" font-size="11">结点地址 165</text>
    <text class="fig-muted" x="234" y="186" text-anchor="middle" font-size="11">130</text>
    <text class="fig-muted" x="384" y="186" text-anchor="middle" font-size="11">135</text>
    <text class="fig-muted" x="534" y="186" text-anchor="middle" font-size="11">170</text>
    <rect class="fig-box-subtle" x="18" y="206" width="314" height="104" rx="6"/>
    <rect class="fig-box-subtle" x="346" y="206" width="316" height="104" rx="6"/>
    <line class="fig-line-accent" x1="146" y1="252" x2="188" y2="252" marker-end="url(#wz-w1-arr-1)"/>
    <line class="fig-line-accent" x1="146" y1="280" x2="188" y2="280" marker-end="url(#wz-w1-arr-1)"/>
    <line class="fig-line-accent" x1="448" y1="264" x2="480" y2="264" marker-end="url(#wz-w1-arr-1)"/>
    <line class="fig-line-accent" x1="564" y1="264" x2="592" y2="264" marker-end="url(#wz-w1-arr-1)"/>
    <rect class="fig-box-blue" x="32" y="238" width="114" height="28" rx="3"/>
    <rect class="fig-box-blue" x="32" y="266" width="114" height="28" rx="3"/>
    <line class="fig-divider" x1="82" y1="238" x2="82" y2="294"/>
    <rect class="fig-box" x="192" y="238" width="124" height="28" rx="3"/>
    <rect class="fig-box" x="192" y="266" width="124" height="28" rx="3"/>
    <rect class="fig-box" x="360" y="246" width="88" height="36" rx="4"/>
    <rect class="fig-box-purple" x="484" y="246" width="80" height="36" rx="4"/>
    <rect class="fig-box-orange" x="596" y="238" width="52" height="52" rx="4"/>
    <text class="fig-title" x="32" y="226" font-size="12.5">③ 索引存储：附加索引表加速定位</text>
    <text class="fig-blue" x="57" y="256" text-anchor="middle" font-size="11">A 类</text>
    <text class="fig-muted" x="114" y="256" text-anchor="middle" font-size="11">块址 1</text>
    <text class="fig-blue" x="57" y="284" text-anchor="middle" font-size="11">B 类</text>
    <text class="fig-muted" x="114" y="284" text-anchor="middle" font-size="11">块址 2</text>
    <text class="fig-label" x="254" y="256" text-anchor="middle" font-size="11">数据区记录块 1</text>
    <text class="fig-label" x="254" y="284" text-anchor="middle" font-size="11">数据区记录块 2</text>
    <text class="fig-title" x="360" y="226" font-size="12.5">④ 散列存储：由关键字直接算出地址</text>
    <text class="fig-label" x="404" y="268" text-anchor="middle" font-size="11.5">key = 37</text>
    <text class="fig-purple" x="524" y="268" text-anchor="middle" font-size="11.5">H(key)</text>
    <text class="fig-orange" x="622" y="261" text-anchor="middle" font-size="11">槽[4]</text>
    <text class="fig-muted" x="622" y="279" text-anchor="middle" font-size="10.5">直接存</text>
  </svg>
  <figcaption>四种基本存储结构对比：顺序靠连续位置、链式靠指针、索引靠索引表、散列靠函数计算</figcaption>
</figure>

> **注意**：顺序存储必须占用**连续**空间，中间不能有空的存储单元，否则无法用位置表示前驱后继，就不再是顺序存储结构。

<figure class="cpd-figure not-content" id="wz-fig-1b">
  <svg viewBox="0 0 680 264" role="img" aria-label="从抽象数据类型 ADT 到存储映象、算法实现与复杂度评价的完整链路">
    <defs>
      <marker id="wz-w1-arr-1b" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <line class="fig-line" x1="340" y1="50" x2="340" y2="70"/>
    <line class="fig-line" x1="100" y1="70" x2="580" y2="70"/>
    <line class="fig-line" x1="100" y1="70" x2="100" y2="90" marker-end="url(#wz-w1-arr-1b)"/>
    <line class="fig-line" x1="260" y1="70" x2="260" y2="90" marker-end="url(#wz-w1-arr-1b)"/>
    <line class="fig-line" x1="420" y1="70" x2="420" y2="90" marker-end="url(#wz-w1-arr-1b)"/>
    <line class="fig-line" x1="580" y1="70" x2="580" y2="90" marker-end="url(#wz-w1-arr-1b)"/>
    <line class="fig-line" x1="100" y1="132" x2="100" y2="150"/>
    <line class="fig-line" x1="260" y1="132" x2="260" y2="150"/>
    <line class="fig-line" x1="420" y1="132" x2="420" y2="150"/>
    <line class="fig-line" x1="580" y1="132" x2="580" y2="150"/>
    <line class="fig-line" x1="100" y1="150" x2="580" y2="150"/>
    <line class="fig-line-accent" x1="340" y1="150" x2="340" y2="168" marker-end="url(#wz-w1-arr-1b)"/>
    <line class="fig-line-accent" x1="340" y1="202" x2="340" y2="220" marker-end="url(#wz-w1-arr-1b)"/>
    <rect class="fig-box-accent" x="150" y="14" width="380" height="36" rx="6"/>
    <rect class="fig-box-blue" x="34" y="92" width="132" height="40" rx="6"/>
    <rect class="fig-box-blue" x="194" y="92" width="132" height="40" rx="6"/>
    <rect class="fig-box-blue" x="354" y="92" width="132" height="40" rx="6"/>
    <rect class="fig-box-blue" x="514" y="92" width="132" height="40" rx="6"/>
    <rect class="fig-box" x="150" y="170" width="380" height="32" rx="6"/>
    <rect class="fig-box-green" x="150" y="222" width="380" height="30" rx="6"/>
    <text class="fig-accent" x="340" y="36" text-anchor="middle" font-size="12.5">抽象数据类型 ADT = (D 数据对象, S 关系集, P 基本操作)</text>
    <text class="fig-blue" x="100" y="110" text-anchor="middle" font-size="12">顺序存储</text>
    <text class="fig-muted" x="100" y="125" text-anchor="middle" font-size="10.5">连续数组</text>
    <text class="fig-blue" x="260" y="110" text-anchor="middle" font-size="12">链式存储</text>
    <text class="fig-muted" x="260" y="125" text-anchor="middle" font-size="10.5">指针链接</text>
    <text class="fig-blue" x="420" y="110" text-anchor="middle" font-size="12">索引存储</text>
    <text class="fig-muted" x="420" y="125" text-anchor="middle" font-size="10.5">索引 + 数据</text>
    <text class="fig-blue" x="580" y="110" text-anchor="middle" font-size="12">散列存储</text>
    <text class="fig-muted" x="580" y="125" text-anchor="middle" font-size="10.5">H(key) 映射</text>
    <text class="fig-label" x="340" y="190" text-anchor="middle" font-size="12">在选定的存储结构上编写类 C / C 语言算法</text>
    <text class="fig-green" x="340" y="241" text-anchor="middle" font-size="12">事前分析：时间复杂度 T(n) 与辅助空间复杂度 S(n) 择优</text>
  </svg>
  <figcaption>数据结构与算法的完整设计链条：逻辑抽象（ADT）→ 存储映象 → 算法实现与复杂度评估</figcaption>
</figure>

### 数据类型与抽象数据类型

**数据类型**：一组性质相同的值的集合，以及定义在该值集上的一组操作的总称。

高级语言中的类型规定了变量的**取值范围**和**可施行的操作**：如 `int` 只能取整数、只能做加减乘除与求模；`char` 只能取字符并做字符运算。程序员无需说明变量占多大空间、如何存储。

**抽象**：从事物中抽取共同的本质属性和关系，舍去个别的、非本质的属性（各式各样的圆 → 圆心 + 半径；各种复数 → 实部 + 虚部）。

**抽象数据类型（ADT）**：从具体问题中抽象出的数学模型，以及定义在该模型上的一组操作。它包括数据模型（逻辑结构）和其上的一组操作，**不涉及计算机内部如何存储与实现**。

> **注意**：ADT 是“概念层”的定义；同一 ADT 可有多种存储结构和多种实现。

### 抽象数据类型的定义格式与实现

形式定义是一个三元组 $(D, S, P)$：$D$ 为数据对象，$S$ 为 $D$ 上关系的集合，$P$ 为对 $D$ 的基本操作集。

固定书写格式：

```text
ADT 抽象数据类型名 {
    数据对象：D = { ... }
    数据关系：R = { ... }
    基本操作：
        操作名(参数表)
            初始条件：...
            操作结果：...
} ADT 抽象数据类型名
```

- 参数表中，需要**带回结果**的参数前加 `&`，称为**引用型参数**（如构造圆 `CreateCircle(&C, r, x, y)` 的圆、缩放图形 `Scale(&G, n)` 的结果图形、复数相加 `Add(z1, z2, &z)` 的和）。
- **初始条件**：操作执行前数据结构及参数应满足的条件，为空可省略；不满足应返回出错信息。
- **操作结果**：操作正常完成时返回的结果或数据结构发生的变化。

C 语言实现分两步：用已有类型定义存储结构，用函数实现操作。

```c
typedef struct {
    float Realpart;
    float Imagepart;
} Complex;                      /* 数据部分：实部、虚部 */

Complex Add(Complex a, Complex b) {
    Complex c;
    c.Realpart = a.Realpart + b.Realpart;
    c.Imagepart = a.Imagepart + b.Imagepart;
    return c;
}
```

- 结构变量用 `.` 取成员，结构指针用 `->` 取成员。
- 引用参数 `&L`：形参是实参的别名，共用同一存储单元，不产生副本；形参改变即实参改变，书写比指针简单，效率比传值高。

> **注意**：类 C 语言省略了语法细节，直接上机需补全——`Status`、`ElemType` 要 typedef，动态内存要包含 `stdlib.h` 并检查分配是否成功。

<figure class="cpd-figure not-content" id="wz-w1-fig-2">
  <svg viewBox="0 0 680 248" role="img" aria-label="ADT 三元组定义与值传递、引用参数内存机制对比">
    <defs>
      <marker id="wz-w1-arr-2" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="18" y="14" width="292" height="218" rx="6"/>
    <rect class="fig-box-subtle" x="324" y="14" width="338" height="218" rx="6"/>
    <line class="fig-line-accent" x1="164" y1="78" x2="164" y2="96" marker-end="url(#wz-w1-arr-2)"/>
    <line class="fig-line-accent" x1="164" y1="140" x2="164" y2="158" marker-end="url(#wz-w1-arr-2)"/>
    <rect class="fig-box-accent" x="34" y="42" width="260" height="36" rx="5"/>
    <rect class="fig-box-blue" x="34" y="98" width="260" height="42" rx="5"/>
    <rect class="fig-box-green" x="34" y="160" width="260" height="58" rx="5"/>
    <text class="fig-title" x="34" y="32" font-size="12.5">ADT 三元组 (D, S, P) 映射 C 实现</text>
    <text class="fig-accent" x="164" y="64" text-anchor="middle" font-size="12">概念层：ADT = (D 对象, S 关系, P 操作)</text>
    <text class="fig-blue" x="164" y="116" text-anchor="middle" font-size="11.5">① 数据部分：typedef struct &#123; ... &#125;</text>
    <text class="fig-muted" x="164" y="132" text-anchor="middle" font-size="10.5">结构变量用 . 访问，结构指针用 -&gt; 访问</text>
    <text class="fig-green" x="164" y="180" text-anchor="middle" font-size="11.5">② 操作部分：Status Op(&amp;L, ...)</text>
    <text class="fig-muted" x="164" y="198" text-anchor="middle" font-size="10.5">校验初始条件 → 执行修改 → 返回操作结果</text>
    <line class="fig-line-dashed" x1="444" y1="72" x2="508" y2="72" marker-end="url(#wz-w1-arr-2)"/>
    <path class="fig-line-accent" d="M 444 166 L 508 166" marker-end="url(#wz-w1-arr-2)"/>
    <path class="fig-line-accent" d="M 444 198 L 508 178" marker-end="url(#wz-w1-arr-2)"/>
    <rect class="fig-box" x="340" y="54" width="104" height="36" rx="4"/>
    <rect class="fig-box-orange" x="512" y="54" width="134" height="36" rx="4"/>
    <rect class="fig-box" x="340" y="148" width="104" height="28" rx="4"/>
    <rect class="fig-box-purple" x="340" y="184" width="104" height="28" rx="4"/>
    <rect class="fig-box-green" x="512" y="152" width="134" height="54" rx="4"/>
    <text class="fig-title" x="340" y="32" font-size="12.5">传值参数 f(L) vs 引用参数 f(&amp;L)</text>
    <text class="fig-label" x="392" y="76" text-anchor="middle" font-size="11.5">实参 a (0x10)</text>
    <text class="fig-orange" x="579" y="71" text-anchor="middle" font-size="11.5">形参副本 (0x90)</text>
    <text class="fig-muted" x="579" y="85" text-anchor="middle" font-size="10">改副本不影响实参</text>
    <text class="fig-muted" x="476" y="64" text-anchor="middle" font-size="10.5">拷贝</text>
    <line class="fig-divider" x1="338" y1="114" x2="648" y2="114"/>
    <text class="fig-accent" x="340" y="136" font-size="11.5">引用传参 &amp;L：形参即实参别名，零拷贝直接改原表</text>
    <text class="fig-label" x="392" y="166" text-anchor="middle" font-size="11.5">实参名 L</text>
    <text class="fig-purple" x="392" y="202" text-anchor="middle" font-size="11.5">引用形参 &amp;L</text>
    <text class="fig-green" x="579" y="174" text-anchor="middle" font-size="11.5">同一存储单元</text>
    <text class="fig-muted" x="579" y="194" text-anchor="middle" font-size="10.5">地址 0x10（共享内存）</text>
  </svg>
  <figcaption>ADT 的两步 C 语言实现与引用参数 &amp;L 共享同一存储单元的内存机制</figcaption>
</figure>

### 算法的定义、特性与设计要求

**算法**：对特定问题求解方法和步骤的描述，是指令的有限序列，每条指令表示一个或多个操作。简单说就是“第一步做什么、第二步做什么”。

描述方式：自然语言、传统流程图（圆角矩形表示起止，平行四边形表示输入输出，矩形表示处理，菱形表示判断）、N-S 流程图、伪代码/类 C 语言、程序代码。

算法与程序：算法是解决问题的方法与过程，同一问题可有多算法；程序是用某种语言对算法的具体实现。**程序 = 数据结构 + 算法**。

五个特性：

| 特性 | 含义 |
| --- | --- |
| 有穷性 | 步骤有限，每一步的执行时间也有限 |
| 确定性 | 每条指令含义确切、无二义；相同输入必得相同输出 |
| 可行性 | 每一步都能用已实现的基本操作完成 |
| 输入 | 有零个或多个输入（输入可内置于算法中） |
| 输出 | 有一个或多个输出，无结果不成立 |

设计要求：**正确性**（对精心选择的典型、苛刻输入能得到满足要求的结果）、**可读性**（算法主要供人阅读交流，晦涩的算法易隐藏错误、难调试）、**健壮性**（非法输入或异常情况能作出反应，不产生莫名其妙的结果，也称鲁棒性）、**高效性**（时间与空间开销尽量小）。

### 语句频度与算法时间的度量

时间效率的度量有两条路：

- **事后统计**：先编成程序再实测。缺点是要先编程，且结果受软硬件环境影响，可能掩盖算法本身的优劣。
- **事前分析**：不实现算法，直接估算其耗费。常用。

$$
T(n)=\sum_{i=1}^{k} t_i \times f_i
$$

$f_i$ 是语句 $i$ 的执行次数，称为**语句频度**；$t_i$ 是执行一次所需时间，由机器指令性能、运算速度、所用语言等软硬件环境决定，与算法本身无关。假设各语句单位时间相同，比较 $T(n)$ 就转化为比较**语句频度之和**，从而脱离具体机器。

例：两个 $n$ 阶矩阵相乘，对三重循环各语句的频度求和，得

$$
T(n)=2n^3+3n^2+2n+1
$$

> **注意**：循环语句本身比循环体多执行一次（最后一次判断条件不成立而退出），数频度时不要漏掉这个 “+1”。

### 渐进时间复杂度与大 O

若存在辅助函数 $f(n)$，使

$$
\lim_{n\to\infty}\frac{T(n)}{f(n)}=c\neq 0
$$

则称 $T(n)$ 与 $f(n)$ **同量级**，记作 $T(n)=O(f(n))$，称 $O(f(n))$ 为算法的**渐进时间复杂度**（简称时间复杂度）。符号 $O$ 取自 order，意为数量级。

其意义：$n$ 充分大时，算法执行时间的**增长率**与 $f(n)$ 的增长率相同。

计算三步：

1. 找出**基本语句**——执行次数最多、对运行时间贡献最大、其重复次数与算法执行时间成正比的语句。循环嵌套中，嵌套层次最深的循环体通常就是。
2. 写出其执行次数关于问题规模 $n$ 的函数（最关键也最难的一步；不便直接计数时用级数求和）。
3. 取该函数的数量级，写成 $O$ 的形式。

**简化定理**：若 $f(n)$ 是 $n$ 的 $m$ 次多项式，则 $T(n)=O(n^m)$——只保留最高次项，并去掉最高次项的系数。所有低次项与常数在 $n\to\infty$ 时对极限无贡献。

问题规模 $n$ 的含义随问题而定：排序为待排序记录数，矩阵相乘为阶数，集合为元素个数，多项式为项数，树为结点数，图为顶点数或边数。

例：

```c
int i = 1;
while (i <= n) i = i * 2;
```

设循环体执行 $x$ 次，则 $i=2^x$，退出条件是 $2^x>n$，故 $x\le \log_2 n$，$T(n)=O(\log n)$。

### 常见复杂度量级及其比较

按数量级由低到高：

$$
O(1) < O(\log n) < O(n) < O(n\log n) < O(n^2) < O(n^3) < O(2^n) < O(n!)
$$

| 量级 | 名称 | $n=32$ 时的量级感受 | 评价 |
| --- | --- | --- | --- |
| $O(1)$ | 常数阶 | 与 $n$ 无关 | 最优 |
| $O(\log n)$ | 对数阶 | 约 5 | 很好，尽量向此靠拢 |
| $O(n)$ | 线性阶 | 32 | 可接受 |
| $O(n\log n)$ | 线性对数阶 | 约 160 | 较好 |
| $O(n^2)$ | 平方阶 | 1024 | 尚可 |
| $O(n^3)$ | 立方阶 | 32768 | 尚可 |
| $O(2^n)$ | 指数阶 | $2^{32}\approx 4.3\times10^9$ | 几乎不可接受 |
| $O(n!)$ | 阶乘阶 | 天文数字 | 不可接受 |

> **注意**：比较大小时只看量级——$10n^2$ 优于 $5n^3$（$n$ 充分大时），不能因系数小就选高阶算法。

<figure class="cpd-figure not-content" id="wz-w1-fig-3">
  <svg viewBox="0 0 680 262" role="img" aria-label="常见时间复杂度量级对比与典型循环语句频度推导">
    <rect class="fig-box-subtle" x="18" y="14" width="322" height="232" rx="6"/>
    <rect class="fig-box-subtle" x="352" y="14" width="310" height="232" rx="6"/>
    <rect class="fig-box-green" x="116" y="44" width="16" height="20" rx="3"/>
    <rect class="fig-box-green" x="116" y="72" width="36" height="20" rx="3"/>
    <rect class="fig-box-blue" x="116" y="100" width="68" height="20" rx="3"/>
    <rect class="fig-box-blue" x="116" y="128" width="104" height="20" rx="3"/>
    <rect class="fig-box-orange" x="116" y="156" width="144" height="20" rx="3"/>
    <rect class="fig-box-orange" x="116" y="184" width="176" height="20" rx="3"/>
    <rect class="fig-box-red" x="116" y="212" width="210" height="20" rx="3"/>
    <text class="fig-title" x="30" y="32" font-size="12.5">n = 32 时各量级执行次数对比（对数刻度示意）</text>
    <text class="fig-label" x="30" y="58" font-size="11.5">O(1)</text>
    <text class="fig-muted" x="140" y="58" font-size="11">1 次（最优）</text>
    <text class="fig-label" x="30" y="86" font-size="11.5">O(log₂n)</text>
    <text class="fig-muted" x="160" y="86" font-size="11">5 次（极优）</text>
    <text class="fig-label" x="30" y="114" font-size="11.5">O(n)</text>
    <text class="fig-muted" x="192" y="114" font-size="11">32 次</text>
    <text class="fig-label" x="30" y="142" font-size="11.5">O(n log₂n)</text>
    <text class="fig-muted" x="228" y="142" font-size="11">160 次</text>
    <text class="fig-label" x="30" y="170" font-size="11.5">O(n²)</text>
    <text class="fig-muted" x="266" y="170" font-size="11">1024</text>
    <text class="fig-label" x="30" y="198" font-size="11.5">O(n³)</text>
    <text class="fig-muted" x="296" y="198" font-size="11">32768</text>
    <text class="fig-red" x="30" y="226" font-size="11.5">O(2ⁿ)</text>
    <text class="fig-red" x="124" y="226" font-size="10.5">4.3×10⁹（爆炸）</text>
    <rect class="fig-box" x="366" y="42" width="282" height="58" rx="5"/>
    <rect class="fig-box" x="366" y="110" width="282" height="58" rx="5"/>
    <rect class="fig-box-accent" x="366" y="178" width="282" height="56" rx="5"/>
    <text class="fig-title" x="366" y="32" font-size="12.5">408 高频语句频度推导速记</text>
    <text class="fig-blue" x="378" y="60" font-size="11.5">① 倍增循环：while (i &lt;= n) i = i * 2;</text>
    <text class="fig-muted" x="378" y="80" font-size="9.5">执行 x 次后 i = 2ˣ &gt; n ⇒ x = ⌊log₂n⌋ + 1 ⇒ O(log n)</text>
    <text class="fig-orange" x="378" y="128" font-size="11.5">② 三角嵌套：for(i=1..n) for(j=1..i) s++;</text>
    <text class="fig-muted" x="378" y="148" font-size="11">频度 ∑i = n(n + 1)/2 = ½n² + ½n ⇒ O(n²)</text>
    <text class="fig-accent" x="378" y="198" font-size="11.5">③ 易错点：循环头判断比循环体多执行 1 次</text>
    <text class="fig-muted" x="378" y="218" font-size="11">for (i = 0; i &lt; n; i++) 判断 n + 1 次，体执行 n 次</text>
  </svg>
  <figcaption>常见渐进时间复杂度量级增长对比与三类高频循环频度推导规律</figcaption>
</figure>

### 最坏、平均、最好情况与大 O 运算规则

有的算法，其基本操作的执行次数不仅取决于规模 $n$，还取决于**输入数据集**。以顺序查找为例（在 $n$ 个元素中找等于 $e$ 的元素）：

- 最好情况：第一个元素即命中，比较 1 次，$O(1)$；
- 最坏情况：最后一个元素命中或查找失败，比较 $n$ 次，$O(n)$；
- 平均情况：约 $n/2$ 次，$O(n)$。

通常考虑**最坏**与**平均**时间复杂度；平均不易计算时用最坏，因为最坏给出了运行时间的上界。

复杂算法可分解为若干易估算的部分，再用大 O 的运算规则合并：

- **加法规则**：$T(n)=T_1(n)+T_2(n)=O(\max\{f_1(n),f_2(n)\})$
- **乘法规则**：$T(n)=T_1(n)\times T_2(n)=O(f_1(n)\times f_2(n))$

### 空间复杂度

**渐进空间复杂度**：算法所需存储空间关于问题规模 $n$ 的函数数量级，记 $S(n)=O(f(n))$。所需空间包括算法本身占用的指令、常数、变量，以及执行时使用的**辅助空间**。

例：将一维数组 $a[0..n-1]$ 就地逆序。

- 算法一：首尾两两交换，共约 $\lfloor n/2\rfloor$ 次，只需一个临时变量。$S(n)=O(1)$，称为**原地工作**。
- 算法二：另开一个同样大小的数组 $b$，倒序复制后再搬回 $a$。$S(n)=O(n)$。

> **注意**：时间与空间常相互矛盾——省时间往往多占空间，省空间往往多花时间。需按实际问题的数据量与机器条件综合权衡。

> **★考点**：给出算法要求分析复杂度时，按“找基本语句 → 写频度函数 → 取最高次项”三步作答；空间复杂度只看**辅助空间**，不计输入数据本身。

<figure class="cpd-figure not-content" id="wz-w1-fig-4">
  <svg viewBox="0 0 680 232" role="img" aria-label="空间复杂度对比：原地逆置 S(n)=O(1) 与辅助数组逆置 S(n)=O(n)">
    <defs>
      <marker id="wz-w1-arr-4s" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="18" y="14" width="318" height="202" rx="6"/>
    <rect class="fig-box-subtle" x="348" y="14" width="314" height="202" rx="6"/>
    <path class="fig-line-accent" d="M 60 80 C 60 44, 240 44, 240 80" marker-start="url(#wz-w1-arr-4s)" marker-end="url(#wz-w1-arr-4s)"/>
    <path class="fig-line" stroke="var(--sl-color-blue)" d="M 105 118 C 105 148, 195 148, 195 118" marker-start="url(#wz-w1-arr-4s)" marker-end="url(#wz-w1-arr-4s)"/>
    <rect class="fig-box-accent" x="38" y="84" width="44" height="32" rx="3"/>
    <rect class="fig-box-blue" x="83" y="84" width="44" height="32" rx="3"/>
    <rect class="fig-box" x="128" y="84" width="44" height="32" rx="3"/>
    <rect class="fig-box-blue" x="173" y="84" width="44" height="32" rx="3"/>
    <rect class="fig-box-accent" x="218" y="84" width="44" height="32" rx="3"/>
    <rect class="fig-box-green" x="272" y="84" width="50" height="32" rx="4"/>
    <text class="fig-title" x="30" y="34" font-size="12.5">算法一：首尾对调原地逆置 S(n) = O(1)</text>
    <text class="fig-accent" x="60" y="104" text-anchor="middle" font-size="12">a₀</text>
    <text class="fig-blue" x="105" y="104" text-anchor="middle" font-size="12">a₁</text>
    <text class="fig-label" x="150" y="104" text-anchor="middle" font-size="12">a₂</text>
    <text class="fig-blue" x="195" y="104" text-anchor="middle" font-size="12">a₃</text>
    <text class="fig-accent" x="240" y="104" text-anchor="middle" font-size="12">a₄</text>
    <text class="fig-green" x="297" y="104" text-anchor="middle" font-size="11.5">temp</text>
    <text class="fig-muted" x="177" y="176" text-anchor="middle" font-size="11">仅用 1 个辅助变量 temp，与规模 n 无关</text>
    <text class="fig-green" x="177" y="198" text-anchor="middle" font-size="11.5">原地工作（In-place）：辅助空间 O(1)</text>
    <line class="fig-line-dashed" x1="406" y1="84" x2="586" y2="124" marker-end="url(#wz-w1-arr-4s)"/>
    <line class="fig-line-dashed" x1="586" y1="84" x2="406" y2="124" marker-end="url(#wz-w1-arr-4s)"/>
    <rect class="fig-box" x="384" y="54" width="44" height="28" rx="3"/>
    <rect class="fig-box" x="429" y="54" width="44" height="28" rx="3"/>
    <rect class="fig-box" x="474" y="54" width="44" height="28" rx="3"/>
    <rect class="fig-box" x="519" y="54" width="44" height="28" rx="3"/>
    <rect class="fig-box" x="564" y="54" width="44" height="28" rx="3"/>
    <rect class="fig-box-orange" x="384" y="128" width="44" height="28" rx="3"/>
    <rect class="fig-box-orange" x="429" y="128" width="44" height="28" rx="3"/>
    <rect class="fig-box-orange" x="474" y="128" width="44" height="28" rx="3"/>
    <rect class="fig-box-orange" x="519" y="128" width="44" height="28" rx="3"/>
    <rect class="fig-box-orange" x="564" y="128" width="44" height="28" rx="3"/>
    <text class="fig-title" x="362" y="34" font-size="12.5">算法二：辅助数组倒序拷贝 S(n) = O(n)</text>
    <text class="fig-muted" x="364" y="72" font-size="11">a[]</text>
    <text class="fig-label" x="406" y="72" text-anchor="middle" font-size="11.5">a₀</text>
    <text class="fig-label" x="451" y="72" text-anchor="middle" font-size="11.5">a₁</text>
    <text class="fig-label" x="496" y="72" text-anchor="middle" font-size="11.5">a₂</text>
    <text class="fig-label" x="541" y="72" text-anchor="middle" font-size="11.5">a₃</text>
    <text class="fig-label" x="586" y="72" text-anchor="middle" font-size="11.5">a₄</text>
    <text class="fig-orange" x="364" y="146" font-size="11">b[]</text>
    <text class="fig-orange" x="406" y="146" text-anchor="middle" font-size="11.5">a₄</text>
    <text class="fig-orange" x="451" y="146" text-anchor="middle" font-size="11.5">a₃</text>
    <text class="fig-orange" x="496" y="146" text-anchor="middle" font-size="11.5">a₂</text>
    <text class="fig-orange" x="541" y="146" text-anchor="middle" font-size="11.5">a₁</text>
    <text class="fig-orange" x="586" y="146" text-anchor="middle" font-size="11.5">a₀</text>
    <text class="fig-muted" x="505" y="176" text-anchor="middle" font-size="11">额外开辟长 n 的数组 b[0..n−1]</text>
    <text class="fig-orange" x="505" y="198" text-anchor="middle" font-size="11.5">辅助空间随 n 线性增长：S(n) = O(n)</text>
  </svg>
  <figcaption>空间复杂度只计辅助空间：原地双指针交换为 O(1)，另开等长辅助数组为 O(n)</figcaption>
</figure>

## 第2章 线性表

### 线性表的定义与逻辑特征

**线性表**：由 $n$（$n\ge 0$）个**具有相同特性**的数据元素构成的**有限序列**，记作

$$
(a_1, a_2, \dots, a_i, \dots, a_n)
$$

三个关键字缺一不可：**序列**（元素有先后次序）、**相同特性**（同一表中元素性质相同）、**有限**。

- $n$ 为元素个数，即**表长**；$n=0$ 时称为**空表**。
- $a_1$ 为**首元**（起始结点），无直接前驱；$a_n$ 为**终端结点**，无直接后继；其余为内部结点。
- 元素的**序号**（位序）表示其在线性表中的位置，$a_i$ 的位序为 $i$。
- $a_{i-1}$ 是 $a_i$ 的**直接前驱**，$a_{i+1}$ 是 $a_i$ 的**直接后继**。

**逻辑特征**：非空线性表中，有且仅有一个开始结点 $a_1$（无前驱）和一个终端结点 $a_n$（无后继）；除首元外每个元素**有且仅有一个**直接前驱，除终端外每个元素**有且仅有一个**直接后继。因此线性表是典型的**一对一线性结构**。

$a_i$ 只是抽象符号，可代表字母、整数、学生记录等，具体含义由问题决定。

> **注意**：同一线性表中所有元素必须具有相同特性（如同为字符、同为某种结构类型的记录）；“有限”与“有序”缺一不可。

### 线性表的典型应用

**一元多项式**：$P_n(x)=p_1x^{e_1}+p_2x^{e_2}+\dots+p_mx^{e_m}$。

- 若每项都齐全（$e_i=i-1$），只需按幂次顺序存系数，**下标即指数**；两多项式相加即对应下标系数相加，$O(m)$。
- **稀疏多项式**：项数很少而指数很大，如 $1+3x^{10000}+2x^{20000}$。若仍按“下标 = 指数”存储，要 20001 个空间却只存 3 项，浪费严重。改为只存非零项的（系数，指数）二元组线性表。
- 两个稀疏多项式求和：两个表从头并行扫描，比较指数——指数小者直接复制到结果表；指数相等则系数相加，和为 0 丢弃、不为 0 插入结果表；某个表扫完，把另一表剩余项全部接上。
  - 顺序存储：结果表长度不定（最多 $m+n$ 项，最少 0 项），数组定大了浪费、定小了溢出，且需额外数组，空间复杂度高。
  - 链式存储：按需分配结点，不必预占连续空间。

**图书信息管理**：以图书记录（书号、书名、定价等）为元素构成线性表，基本操作是查找、插入、删除、修改、排序、计数。同一逻辑结构可选顺序表或链表，需按操作特点选择存储结构，再实现基本操作。

> 结论：实际问题先抽象出共性的逻辑结构（线性表）→ 定义其基本操作（ADT）→ 选择存储结构 → 在存储结构上实现算法。

### 线性表的抽象数据类型

```text
ADT List {
    数据对象：D = { a_i | a_i ∈ ElemSet, i = 1,2,...,n, n ≥ 0 }
    数据关系：R = { <a_{i-1}, a_i> | a_{i-1}, a_i ∈ D, i = 2,...,n }
    基本操作：
        InitList(&L);  DestroyList(&L);  ClearList(&L);
        ListEmpty(L);  ListLength(L);
        GetElem(L, i, &e);
        LocateElem(L, e, compare());
        PriorElem(L, cur_e, &pre_e);
        NextElem(L, cur_e, &next_e);
        ListInsert(&L, i, e);
        ListDelete(&L, i, &e);
        ListTraverse(L, visit());
} ADT List
```

数据关系用序偶 $<a_{i-1},a_i>$ 表示：$a_{i-1}$ 是 $a_i$ 的前驱，$a_i$ 是 $a_{i-1}$ 的后继。这些操作只规定“做什么”，不规定“怎么做”——它们是**逻辑结构上定义的运算**，具体实现取决于存储结构。

### 基本操作及其合法条件

| 操作 | 作用 | 初始条件 / 合法范围 | 操作结果 |
| --- | --- | --- | --- |
| `InitList(&L)` | 初始化 | — | 构造一个空表 |
| `DestroyList(&L)` | 销毁 | 表已存在 | 表本身从内存中消失 |
| `ClearList(&L)` | 清空 | 表已存在 | 表仍在，但重置为空表 |
| `ListEmpty(L)` | 判空 | 表已存在 | 空返回真，否则假 |
| `ListLength(L)` | 求表长 | 表已存在 | 返回元素个数 $n$ |
| `GetElem(L,i,&e)` | 取值 | 表存在，$1\le i\le n$ | 用 $e$ 返回第 $i$ 个元素 |
| `LocateElem(L,e,compare())` | 按值查找 | 表已存在 | 返回第一个满足 `compare` 的元素位序，找不到返回 0 |
| `PriorElem(L,cur_e,&pre_e)` | 求前驱 | 表存在，`cur_e` 不是首元 | 用 `pre_e` 返回前驱，否则失败 |
| `NextElem(L,cur_e,&next_e)` | 求后继 | 表存在，`cur_e` 不是终端 | 用 `next_e` 返回后继，否则失败 |
| `ListInsert(&L,i,e)` | 插入 | 表存在，$1\le i\le n+1$ | 第 $i$ 位插入 $e$，表长 $+1$ |
| `ListDelete(&L,i,&e)` | 删除 | 表存在，$1\le i\le n$ | 删除第 $i$ 个元素并由 $e$ 返回，表长 $-1$ |
| `ListTraverse(L,visit())` | 遍历 | 表已存在 | 依次对每个元素调用 `visit` |

- 插入位置上限是 $n+1$：可以插在最后一个元素**之后**；下限是 1，不能插到首元之前。
- 删除位置范围是 $1\sim n$：不能删除第 $n+1$ 个（不存在）。
- 销毁与清空的区别在于表本身是否还在内存中。

> **★考点**：插入 $1\le i\le n+1$，删除 $1\le i\le n$——差一位，是选择题高频陷阱。

<figure class="cpd-figure not-content" id="wz-w1-fig-5">
  <svg viewBox="0 0 680 228" role="img" aria-label="线性表一对一前驱后继关系及插入删除合法位序范围对比">
    <defs>
      <marker id="wz-w1-arr-5a" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="18" y="14" width="644" height="200" rx="6"/>
    <line class="fig-line-accent" x1="158" y1="92" x2="210" y2="92" marker-end="url(#wz-w1-arr-5a)"/>
    <line class="fig-line-accent" x1="294" y1="92" x2="346" y2="92" marker-end="url(#wz-w1-arr-5a)"/>
    <line class="fig-line-accent" x1="430" y1="92" x2="482" y2="92" marker-end="url(#wz-w1-arr-5a)"/>
    <line class="fig-line" stroke="var(--sl-color-green)" x1="74" y1="46" x2="74" y2="70" marker-end="url(#wz-w1-arr-5a)"/>
    <line class="fig-line" stroke="var(--sl-color-green)" x1="184" y1="46" x2="184" y2="70" marker-end="url(#wz-w1-arr-5a)"/>
    <line class="fig-line" stroke="var(--sl-color-green)" x1="320" y1="46" x2="320" y2="70" marker-end="url(#wz-w1-arr-5a)"/>
    <line class="fig-line" stroke="var(--sl-color-green)" x1="456" y1="46" x2="456" y2="70" marker-end="url(#wz-w1-arr-5a)"/>
    <line class="fig-line" stroke="var(--sl-color-green)" x1="606" y1="46" x2="606" y2="70" marker-end="url(#wz-w1-arr-5a)"/>
    <rect class="fig-box-accent" x="74" y="72" width="84" height="40" rx="5"/>
    <rect class="fig-box" x="210" y="72" width="84" height="40" rx="5"/>
    <rect class="fig-box" x="346" y="72" width="84" height="40" rx="5"/>
    <rect class="fig-box-blue" x="482" y="72" width="84" height="40" rx="5"/>
    <rect class="fig-box-green" x="34" y="156" width="298" height="42" rx="5"/>
    <rect class="fig-box-orange" x="348" y="156" width="298" height="42" rx="5"/>
    <text class="fig-green" x="74" y="38" text-anchor="middle" font-size="11">插 i=1</text>
    <text class="fig-green" x="184" y="38" text-anchor="middle" font-size="11">插 i=2</text>
    <text class="fig-green" x="320" y="38" text-anchor="middle" font-size="11">插 i=3</text>
    <text class="fig-green" x="456" y="38" text-anchor="middle" font-size="11">插 i=4</text>
    <text class="fig-green" x="606" y="38" text-anchor="middle" font-size="11">插 i=n+1(表尾后)</text>
    <text class="fig-accent" x="116" y="96" text-anchor="middle" font-size="12.5">a₁（首元）</text>
    <text class="fig-label" x="252" y="96" text-anchor="middle" font-size="12.5">a₂</text>
    <text class="fig-label" x="388" y="96" text-anchor="middle" font-size="12.5">a₃</text>
    <text class="fig-blue" x="524" y="96" text-anchor="middle" font-size="12.5">a₄（终端）</text>
    <text class="fig-orange" x="116" y="132" text-anchor="middle" font-size="11">删/查 i=1</text>
    <text class="fig-orange" x="252" y="132" text-anchor="middle" font-size="11">删/查 i=2</text>
    <text class="fig-orange" x="388" y="132" text-anchor="middle" font-size="11">删/查 i=3</text>
    <text class="fig-orange" x="524" y="132" text-anchor="middle" font-size="11">删/查 i=4(n)</text>
    <text class="fig-green" x="183" y="174" text-anchor="middle" font-size="11.5">ListInsert(&amp;L, i, e) 合法范围：1 ≤ i ≤ n + 1</text>
    <text class="fig-muted" x="183" y="191" text-anchor="middle" font-size="10.5">共 n + 1 个可插空隙（含表尾元素之后）</text>
    <text class="fig-orange" x="497" y="174" text-anchor="middle" font-size="11.5">ListDelete / GetElem 合法范围：1 ≤ i ≤ n</text>
    <text class="fig-muted" x="497" y="191" text-anchor="middle" font-size="10.5">共 n 个已有元素位序（第 n + 1 位不存在）</text>
  </svg>
  <figcaption>线性表（以 n = 4 为例）：首元无前驱、终端无后继，插入合法位序比删除多一个 n + 1</figcaption>
</figure>

### 顺序表的存储结构与地址计算

**顺序表示**（顺序存储结构、顺序映像）：用一组**地址连续**的存储单元依次存放线性表的元素，使逻辑上相邻的元素在物理位置上也相邻，用存储单元的先后位置表示前驱后继关系。逻辑结构与存储结构一致。

设每个元素占用 $l$ 个存储单元，第一个元素的存储地址（**基地址/首地址**）为 $LOC(a_1)$，则第 $i$ 个元素的地址为

$$
LOC(a_i)=LOC(a_1)+(i-1)\times l
$$

由公式可见：只要知道基地址和 $l$，任意元素的地址都可由**一次计算**得到，与表长 $n$ 无关，时间为 $O(1)$。这种存取方式称为**随机存取**。

<figure class="cpd-figure not-content" id="wz-fig-2">
  <svg viewBox="0 0 680 246" role="img" aria-label="顺序表内存布局、容量 MAXSIZE 与随机存取地址计算公式">
    <defs>
      <marker id="wz-w1-arr-2s" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="18" y="14" width="644" height="218" rx="6"/>
    <line class="fig-line-accent" x1="258" y1="168" x2="258" y2="146" marker-end="url(#wz-w1-arr-2s)"/>
    <rect class="fig-box" x="34" y="62" width="64" height="40"/>
    <rect class="fig-box" x="98" y="62" width="64" height="40"/>
    <rect class="fig-box" x="162" y="62" width="64" height="40"/>
    <rect class="fig-box-accent" x="226" y="62" width="64" height="40"/>
    <rect class="fig-box" x="290" y="62" width="64" height="40"/>
    <rect class="fig-box" x="354" y="62" width="64" height="40"/>
    <rect class="fig-box-dashed" x="418" y="62" width="64" height="40"/>
    <rect class="fig-box-dashed" x="482" y="62" width="64" height="40"/>
    <rect class="fig-box-blue" x="562" y="62" width="84" height="40" rx="5"/>
    <rect class="fig-box-green" x="34" y="172" width="612" height="46" rx="5"/>
    <text class="fig-title" x="34" y="34" font-size="12.5">顺序表 SqList：连续数组 data[0..MAXSIZE−1] + 当前表长 length（设 l = 8B）</text>
    <text class="fig-muted" x="66" y="54" text-anchor="middle" font-size="10.5">位序 1</text>
    <text class="fig-muted" x="130" y="54" text-anchor="middle" font-size="10.5">位序 2</text>
    <text class="fig-muted" x="194" y="54" text-anchor="middle" font-size="10.5">位序 3</text>
    <text class="fig-accent" x="258" y="54" text-anchor="middle" font-size="10.5">位序 4</text>
    <text class="fig-muted" x="322" y="54" text-anchor="middle" font-size="10.5">位序 5</text>
    <text class="fig-muted" x="386" y="54" text-anchor="middle" font-size="10.5">位序 6</text>
    <text class="fig-muted" x="482" y="54" text-anchor="middle" font-size="10.5">空闲容量（至 MAXSIZE−1）</text>
    <text class="fig-label" x="66" y="86" text-anchor="middle" font-size="12.5">a₁</text>
    <text class="fig-label" x="130" y="86" text-anchor="middle" font-size="12.5">a₂</text>
    <text class="fig-label" x="194" y="86" text-anchor="middle" font-size="12.5">a₃</text>
    <text class="fig-accent" x="258" y="86" text-anchor="middle" font-size="12.5">a₄</text>
    <text class="fig-label" x="322" y="86" text-anchor="middle" font-size="12.5">a₅</text>
    <text class="fig-label" x="386" y="86" text-anchor="middle" font-size="12.5">a₆</text>
    <text class="fig-muted" x="450" y="86" text-anchor="middle" font-size="11">空闲</text>
    <text class="fig-muted" x="514" y="86" text-anchor="middle" font-size="11">…</text>
    <text class="fig-blue" x="604" y="80" text-anchor="middle" font-size="12.5">6</text>
    <text class="fig-muted" x="604" y="96" text-anchor="middle" font-size="10.5">L.length</text>
    <text class="fig-muted" x="66" y="118" text-anchor="middle" font-size="11">[0]</text>
    <text class="fig-muted" x="130" y="118" text-anchor="middle" font-size="11">[1]</text>
    <text class="fig-muted" x="194" y="118" text-anchor="middle" font-size="11">[2]</text>
    <text class="fig-accent" x="258" y="118" text-anchor="middle" font-size="11">[3]</text>
    <text class="fig-muted" x="322" y="118" text-anchor="middle" font-size="11">[4]</text>
    <text class="fig-muted" x="386" y="118" text-anchor="middle" font-size="11">[5]</text>
    <text class="fig-muted" x="450" y="118" text-anchor="middle" font-size="11">[6]</text>
    <text class="fig-muted" x="514" y="118" text-anchor="middle" font-size="11">[M−1]</text>
    <text class="fig-muted" x="66" y="138" text-anchor="middle" font-size="11">2000</text>
    <text class="fig-muted" x="130" y="138" text-anchor="middle" font-size="11">2008</text>
    <text class="fig-muted" x="194" y="138" text-anchor="middle" font-size="11">2016</text>
    <text class="fig-accent" x="258" y="138" text-anchor="middle" font-size="11">2024</text>
    <text class="fig-muted" x="322" y="138" text-anchor="middle" font-size="11">2032</text>
    <text class="fig-muted" x="386" y="138" text-anchor="middle" font-size="11">2040</text>
    <text class="fig-green" x="340" y="191" text-anchor="middle" font-size="12">随机存取 O(1)：LOC(aᵢ) = LOC(a₁) + (i − 1) × l　例：LOC(a₄) = 2000 + (4 − 1) × 8 = 2024</text>
    <text class="fig-muted" x="340" y="209" text-anchor="middle" font-size="11">易错点：逻辑位序 i 从 1 计，C 数组下标从 0 计（aᵢ 存于 data[i − 1]）；length ≤ MAXSIZE</text>
  </svg>
  <figcaption>顺序表内存结构：已用区 length 与预分配容量 MAXSIZE 分离，按位序 O(1) 计算物理地址</figcaption>
</figure>

> **注意**：逻辑位序从 1 开始，数组下标从 0 开始，$a_i$ 存于 `data[i-1]`。这一“差一”是所有顺序表算法的易错点。

### 顺序表的类型定义

数组长度固定，而线性表的长度可变（插入增、删除减），因此顺序表需要**两部分**描述：一个数组存放元素，一个整数记录当前元素个数。

MAXSIZE 为预定义常量（如 100），`ElemType` 为元素类型。

```c
typedef struct {
    ElemType data[MAXSIZE];   /* 静态分配，MAXSIZE 为容量上限 */
    int length;               /* 当前元素个数 */
} SqList;
```

也可动态分配：

```c
typedef struct {
    ElemType *data;           /* 动态数组的基地址 */
    int length;
} SqList;

/* 初始化时分配：L.data = (ElemType *)malloc(sizeof(ElemType) * MAXSIZE); */
```

- `ElemType` 按具体问题替换（字符、`float`、多项式项、图书记录），或用 `typedef` 起别名。
- 模板中只需改**数组容量**和**元素类型**，即可用于多项式、图书表等不同问题。
- 普通变量用 `L.data[i]`、`L.length`；若 `L` 是结构指针，则用 `L->data`、`L->length`。

> **注意**：`typedef struct {...} SqList;` 只是定义类型，**定义变量时才分配空间**；`MAXSIZE` 是容量上限，`length` 是当前实际元素数，二者不可混用。

### 顺序表上的简单操作

```c
Status InitList(SqList &L) {          /* 构造空表 */
    L.data = (ElemType *)malloc(sizeof(ElemType) * MAXSIZE);
    if (!L.data) return OVERFLOW;     /* 分配失败 */
    L.length = 0;
    return OK;
}

void DestroyList(SqList &L) {         /* 销毁：释放数组，表不复存在 */
    if (L.data) free(L.data);
}

void ClearList(SqList &L) { L.length = 0; }   /* 清空：表还在，元素数为 0 */

int ListEmpty(SqList L)  { return L.length == 0; }

int ListLength(SqList L) { return L.length; }

Status GetElem(SqList L, int i, ElemType &e) {  /* 取第 i 个元素 */
    if (i < 1 || i > L.length) return ERROR;    /* 位序越界 */
    e = L.data[i - 1];
    return OK;
}
```

- `InitList`、`DestroyList`、`ClearList` 的参数带 `&L`，因为要修改表本身（分配/释放/改表长）。
- `&L` 是引用型参数：形参是实参的别名，二者共用同一存储单元，不产生副本，形参改变即实参改变；传值只复制副本（不改实参），传指针需反复解引用、易错，故算法中普遍用引用。
- `GetElem` 只执行常数条语句，$T(n)=O(1)$——这正是随机存取的体现；链式存储做不到，必须从头走。
- 常量 `OK=1`、`ERROR=0`、`OVERFLOW=-2` 需预先定义，否则上机报“未定义”。

> **注意**：`ClearList` 与 `DestroyList` 看起来相似，区别是表本身是否还存在于内存中。

### 顺序表的按值查找

在表中查找与给定值 $e$ 相等的元素，返回其**位序**；找不到返回 0。

```c
int LocateElem(SqList L, ElemType e) {
    for (int i = 0; i < L.length; i++)
        if (L.data[i] == e) return i + 1;   /* 下标 +1 才是位序 */
    return 0;                               /* 查找失败 */
}
```

复杂度分析：设各元素被查找的概率相等，$p_i=1/n$，查第 $i$ 个元素需比较 $i$ 次，则平均查找长度

$$
ASL=\sum_{i=1}^{n}p_i\cdot i=\frac{1}{n}\sum_{i=1}^{n}i=\frac{1}{n}\cdot\frac{n(n+1)}{2}=\frac{n+1}{2}
$$

即平均比较约 $n/2$ 次，$T(n)=O(n)$；最坏（查找失败）比较 $n$ 次。

> **★考点**：ASL 是“概率 × 比较次数”的累加，即期望值；$1+2+\dots+n=\dfrac{n(n+1)}{2}$ 是等差数列求和，别与插入的移动次数公式混淆。

### 顺序表的插入

在第 $i$ 个位置插入元素 $e$（$1\le i\le n+1$）：把第 $i$ 个到第 $n$ 个元素**依次后移一位**，空出第 $i$ 位，再放入 $e$，表长加一。

后移必须**从最后一个元素开始**，否则先移前面的元素会覆盖后面的数据。

```c
Status ListInsert(SqList &L, int i, ElemType e) {
    if (i < 1 || i > L.length + 1) return ERROR;   /* 位置不合法 */
    if (L.length == MAXSIZE) return ERROR;         /* 存储空间已满 */
    for (int j = L.length - 1; j >= i - 1; j--)
        L.data[j + 1] = L.data[j];                 /* 从后往前依次后移 */
    L.data[i - 1] = e;                             /* 空出的位置放新元素 */
    L.length++;                                    /* 表长加一 */
    return OK;
}
```

三种情况：

- 插在表尾（$i=n+1$）：移动 0 次，直接赋值，最快。
- 插在表头（$i=1$）：$n$ 个元素全部后移，最慢。
- 插在中间（$i$）：移动 $n-i+1$ 次。

| 插入位置 $i$ | $1$ | $2$ | $\dots$ | $n$ | $n+1$ |
| --- | --- | --- | --- | --- | --- |
| 移动次数 $n-i+1$ | $n$ | $n-1$ | $\dots$ | $1$ | $0$ |

**过程拆解**：`[a1,a2,a3,a4,a5,a6]` 在第 3 位插入 `X`（$n=6$）：

| 步骤 | 动作 | 结果 |
|:---:|:---|:---|
| 1 | 从 `a6` 开始依次后移 | `a7=a6, a6=a5, a5=a4, a4=a3` |
| 2 | 空出的 `data[2]` 写入 `X` | `[a1,a2,X,a3,a4,a5,a6]` |
| 3 | `length++` | 长度 $6\to7$ |

> **注意**：先判位置是否合法，再判表是否已满（`length == MAXSIZE`），两个判断顺序与返回值都不能省。

### 插入算法的复杂度分析

$n+1$ 个合法插入位置等概率出现，$p_i=\dfrac{1}{n+1}$，移动次数为 $n-i+1$，则平均移动次数

$$
E_{ins}=\frac{1}{n+1}\sum_{i=1}^{n+1}(n-i+1)=\frac{1}{n+1}\cdot\frac{n(n+1)}{2}=\frac{n}{2}
$$

- 最好情况 $O(1)$（表尾插入），最坏情况 $O(n)$（表头插入），平均 $O(n)$。
- 辅助空间只有一个循环变量，$S(n)=O(1)$。

> **★考点**：平均移动 $n/2$ 次，说明插入的主要开销是**移动元素**（访问物理位置并赋值），表越长越慢。这是顺序表的结构性缺陷，不是代码写法的缺陷。

### 顺序表的删除

删除第 $i$ 个元素（$1\le i\le n$），并用 $e$ 返回其值：把第 $i+1$ 个到第 $n$ 个元素**依次前移一位**，表长减一。

前移必须**从前往后**（先移 $a_{i+1}$ 到第 $i$ 位），顺序反了同样会覆盖数据。

```c
Status ListDelete(SqList &L, int i, ElemType &e) {
    if (i < 1 || i > L.length) return ERROR;   /* 删除位置不合法 */
    e = L.data[i - 1];                         /* 保存被删元素，不需要时可省 */
    for (int j = i; j < L.length; j++)
        L.data[j - 1] = L.data[j];             /* 从前往后依次前移 */
    L.length--;                                /* 表长减一 */
    return OK;
}
```

移动次数为 $n-i$：删表尾移动 0 次；删表头移动 $n-1$ 次。等概率下平均移动次数

$$
E_{del}=\frac{1}{n}\sum_{i=1}^{n}(n-i)=\frac{1}{n}\cdot\frac{n(n-1)}{2}=\frac{n-1}{2}
$$

$T(n)=O(n)$，$S(n)=O(1)$。

**过程拆解**：删除 `[a1,a2,a3,a4,a5,a6]` 的第 3 位：

| 步骤 | 动作 | 结果 |
|:---:|:---|:---|
| 1 | 保存 `e = data[2] = a3` | 待返回 |
| 2 | 从 `a4` 开始依次前移 | `data[2]=a4, data[3]=a5, data[4]=a6` |
| 3 | `length--` | `[a1,a2,a4,a5,a6]`，长度 $6\to5$ |

> **注意**：插入从**后往前**移、删除从**前往后**移；插入移动的是插入位及之后的元素，删除移动的是被删元素**之后**的元素。

<figure class="cpd-figure not-content" id="wz-w1-fig-6">
  <svg viewBox="0 0 680 264" role="img" aria-label="顺序表插入从后往前移动与删除从前往后移动过程对比">
    <defs>
      <marker id="wz-w1-arr-6s" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="18" y="14" width="644" height="114" rx="6"/>
    <path class="fig-line-accent" d="M 380 58 C 392 38, 428 38, 440 58" marker-end="url(#wz-w1-arr-6s)"/>
    <path class="fig-line-accent" d="M 316 58 C 328 38, 364 38, 376 58" marker-end="url(#wz-w1-arr-6s)"/>
    <path class="fig-line-accent" d="M 252 58 C 264 38, 300 38, 312 58" marker-end="url(#wz-w1-arr-6s)"/>
    <path class="fig-line-accent" d="M 188 58 C 200 38, 236 38, 248 58" marker-end="url(#wz-w1-arr-6s)"/>
    <rect class="fig-box" x="34" y="62" width="60" height="36"/>
    <rect class="fig-box" x="98" y="62" width="60" height="36"/>
    <rect class="fig-box-green" x="162" y="62" width="60" height="36"/>
    <rect class="fig-box-blue" x="226" y="62" width="60" height="36"/>
    <rect class="fig-box-blue" x="290" y="62" width="60" height="36"/>
    <rect class="fig-box-blue" x="354" y="62" width="60" height="36"/>
    <rect class="fig-box-blue" x="418" y="62" width="60" height="36"/>
    <rect class="fig-box" x="494" y="50" width="152" height="62" rx="5"/>
    <text class="fig-title" x="34" y="34" font-size="12.5">插入 ListInsert(L, i=3, X)：先从表尾往前依次后移（① a₆→② a₅→③ a₄→④ a₃），再写入 X</text>
    <text class="fig-label" x="64" y="84" text-anchor="middle" font-size="12">a₁</text>
    <text class="fig-label" x="128" y="84" text-anchor="middle" font-size="12">a₂</text>
    <text class="fig-green" x="192" y="84" text-anchor="middle" font-size="12">X (新)</text>
    <text class="fig-blue" x="256" y="84" text-anchor="middle" font-size="12">a₃</text>
    <text class="fig-blue" x="320" y="84" text-anchor="middle" font-size="12">a₄</text>
    <text class="fig-blue" x="384" y="84" text-anchor="middle" font-size="12">a₅</text>
    <text class="fig-blue" x="448" y="84" text-anchor="middle" font-size="12">a₆</text>
    <text class="fig-muted" x="64" y="114" text-anchor="middle" font-size="10.5">[0]</text>
    <text class="fig-muted" x="128" y="114" text-anchor="middle" font-size="10.5">[1]</text>
    <text class="fig-green" x="192" y="114" text-anchor="middle" font-size="10.5">[2] (i−1)</text>
    <text class="fig-muted" x="256" y="114" text-anchor="middle" font-size="10.5">[3]</text>
    <text class="fig-muted" x="320" y="114" text-anchor="middle" font-size="10.5">[4]</text>
    <text class="fig-muted" x="384" y="114" text-anchor="middle" font-size="10.5">[5]</text>
    <text class="fig-muted" x="448" y="114" text-anchor="middle" font-size="10.5">[6]</text>
    <text class="fig-accent" x="570" y="74" text-anchor="middle" font-size="11.5">移动 n − i + 1 次</text>
    <text class="fig-muted" x="570" y="96" text-anchor="middle" font-size="11">平均 E_ins = n / 2</text>
    <rect class="fig-box-subtle" x="18" y="138" width="644" height="112" rx="6"/>
    <path class="fig-line" stroke="var(--sl-color-orange)" d="M 252 182 C 240 162, 204 162, 192 182" marker-end="url(#wz-w1-arr-6s)"/>
    <path class="fig-line" stroke="var(--sl-color-orange)" d="M 316 182 C 304 162, 268 162, 256 182" marker-end="url(#wz-w1-arr-6s)"/>
    <path class="fig-line" stroke="var(--sl-color-orange)" d="M 380 182 C 368 162, 332 162, 320 182" marker-end="url(#wz-w1-arr-6s)"/>
    <rect class="fig-box" x="34" y="186" width="60" height="36"/>
    <rect class="fig-box" x="98" y="186" width="60" height="36"/>
    <rect class="fig-box-orange" x="162" y="186" width="60" height="36"/>
    <rect class="fig-box-orange" x="226" y="186" width="60" height="36"/>
    <rect class="fig-box-orange" x="290" y="186" width="60" height="36"/>
    <rect class="fig-box-dashed" x="354" y="186" width="60" height="36"/>
    <rect class="fig-box" x="494" y="174" width="152" height="62" rx="5"/>
    <text class="fig-title" x="34" y="158" font-size="12.5">删除 ListDelete(L, i=3, e)：先存 e = a₃，再从前往后依次前移（① a₄→② a₅→③ a₆）</text>
    <text class="fig-label" x="64" y="208" text-anchor="middle" font-size="12">a₁</text>
    <text class="fig-label" x="128" y="208" text-anchor="middle" font-size="12">a₂</text>
    <text class="fig-orange" x="192" y="208" text-anchor="middle" font-size="12">a₄</text>
    <text class="fig-orange" x="256" y="208" text-anchor="middle" font-size="12">a₅</text>
    <text class="fig-orange" x="320" y="208" text-anchor="middle" font-size="12">a₆</text>
    <text class="fig-muted" x="384" y="208" text-anchor="middle" font-size="11">length−−</text>
    <text class="fig-muted" x="64" y="238" text-anchor="middle" font-size="10.5">[0]</text>
    <text class="fig-muted" x="128" y="238" text-anchor="middle" font-size="10.5">[1]</text>
    <text class="fig-orange" x="192" y="238" text-anchor="middle" font-size="10.5">[2] 覆盖 a₃</text>
    <text class="fig-muted" x="256" y="238" text-anchor="middle" font-size="10.5">[3]</text>
    <text class="fig-muted" x="320" y="238" text-anchor="middle" font-size="10.5">[4]</text>
    <text class="fig-orange" x="570" y="198" text-anchor="middle" font-size="11.5">移动 n − i 次</text>
    <text class="fig-muted" x="570" y="220" text-anchor="middle" font-size="11">平均 E_del = (n−1)/2</text>
  </svg>
  <figcaption>顺序表增删方向铁律：插入从表尾往回后移防覆盖，删除从被删位后继往前前移</figcaption>
</figure>

> **交互演示**：[顺序表插入与删除](/lab/chapter-2/#lab-seqInsert)

### 顺序表小结

- **存储**：以物理位置相邻表示逻辑相邻，逻辑结构与存储结构一致；逻辑位序 $i$ 对应下标 $i-1$。
- **随机存取**：$LOC(a_i)=LOC(a_1)+(i-1)l$，任意元素可一步定位，$O(1)$，可粗略认为访问各元素耗时相等。
- **基本运算**：插入、删除、按值查找均为 $O(n)$；三者空间复杂度均为 $O(1)$。
- **存储密度**：结点本身占的存储量 ÷ 结点结构占的存储量 = 1（不额外存指针），是最大情形。

| 优点 | 缺点 |
| --- | --- |
| 存储密度大（=1），空间利用率高 | 插入/删除需移动大量元素，$O(n)$，效率低 |
| 可随机存取，按位序取值 $O(1)$ | 需预分配足够大的连续空间：定大了浪费，定小了溢出 |
| 实现简单，下标访问直观 | 容量静态固定，元素个数不能自由扩充，不够灵活 |

适用场景：表长相对稳定、以存取为主、插入删除较少的线性表。若元素个数变化大或频繁插删，应改用链式存储。

### 链式存储与链表的基本概念

顺序表以**物理位置相邻**表示逻辑相邻，可随机存取，但插入删除要移动大量元素、空间大小固定（多了溢出、少了浪费）。链式存储则用**任意存储单元**存放元素，逻辑次序与物理次序不必一致，靠额外存储的地址描述前驱后继关系。

结点由两部分构成：**数据域** `data` 存数据元素本身，**指针域** `next` 存后继结点的地址（指针）。$n$ 个元素对应 $n$ 个结点，结点由指针链串接起来，就是**链表**（线性表的链式存储结构）。

<figure class="cpd-figure not-content" id="wz-fig-3">
  <svg viewBox="0 0 680 286" role="img" aria-label="单链表结点结构、带头结点与不带头结点的非空表及空表对比">
    <defs>
      <marker id="wz-w1-arr-3" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="18" y="14" width="644" height="50" rx="6"/>
    <rect class="fig-box" x="116" y="21" width="94" height="34" rx="4"/>
    <rect class="fig-box-blue" x="210" y="21" width="76" height="34" rx="4"/>
    <text class="fig-title" x="32" y="42" font-size="12.5">结点结构</text>
    <text class="fig-label" x="163" y="42" text-anchor="middle" font-size="12.5">data</text>
    <text class="fig-blue" x="248" y="42" text-anchor="middle" font-size="12.5">next</text>
    <text class="fig-muted" x="302" y="42" font-size="11.5">LNode = 数据域（存元素）+ 指针域（存后继结点地址）</text>
    <rect class="fig-box-subtle" x="18" y="74" width="644" height="98" rx="6"/>
    <line class="fig-line-accent" x1="50" y1="126" x2="78" y2="126" marker-end="url(#wz-w1-arr-3)"/>
    <line class="fig-line-accent" x1="168" y1="126" x2="196" y2="126" marker-end="url(#wz-w1-arr-3)"/>
    <line class="fig-line-accent" x1="286" y1="126" x2="314" y2="126" marker-end="url(#wz-w1-arr-3)"/>
    <line class="fig-line-accent" x1="404" y1="126" x2="432" y2="126" marker-end="url(#wz-w1-arr-3)"/>
    <line class="fig-line-accent" x1="564" y1="126" x2="584" y2="126" marker-end="url(#wz-w1-arr-3)"/>
    <rect class="fig-box-purple" x="80" y="108" width="88" height="36" rx="4"/>
    <line class="fig-divider" x1="138" y1="108" x2="138" y2="144"/>
    <rect class="fig-box" x="198" y="108" width="88" height="36" rx="4"/>
    <line class="fig-divider" x1="256" y1="108" x2="256" y2="144"/>
    <rect class="fig-box" x="316" y="108" width="88" height="36" rx="4"/>
    <line class="fig-divider" x1="374" y1="108" x2="374" y2="144"/>
    <rect class="fig-box" x="434" y="108" width="88" height="36" rx="4"/>
    <line class="fig-divider" x1="492" y1="108" x2="492" y2="144"/>
    <rect class="fig-box-purple" x="586" y="108" width="64" height="36" rx="4"/>
    <line class="fig-divider" x1="624" y1="108" x2="624" y2="144"/>
    <text class="fig-title" x="32" y="95" font-size="12.5">带头结点（推荐）：头结点不计入表长，首元与普通结点操作统一</text>
    <text class="fig-accent" x="38" y="130" text-anchor="middle" font-size="12.5">L</text>
    <text class="fig-purple" x="109" y="130" text-anchor="middle" font-size="11.5">头结点</text>
    <circle class="fig-dot" cx="153" cy="126" r="2.8"/>
    <text class="fig-label" x="227" y="130" text-anchor="middle" font-size="12">a₁(首元)</text>
    <circle class="fig-dot" cx="271" cy="126" r="2.8"/>
    <text class="fig-label" x="345" y="130" text-anchor="middle" font-size="12">a₂</text>
    <circle class="fig-dot" cx="389" cy="126" r="2.8"/>
    <text class="fig-label" x="463" y="130" text-anchor="middle" font-size="12">aₙ</text>
    <text class="fig-muted" x="507" y="130" text-anchor="middle" font-size="12">∧</text>
    <text class="fig-muted" x="605" y="95" text-anchor="middle" font-size="10.5">空表：L-&gt;next == NULL</text>
    <text class="fig-accent" x="552" y="130" text-anchor="middle" font-size="12">L</text>
    <text class="fig-purple" x="605" y="130" text-anchor="middle" font-size="11">头</text>
    <text class="fig-muted" x="637" y="130" text-anchor="middle" font-size="12">∧</text>
    <text class="fig-muted" x="109" y="162" text-anchor="middle" font-size="10.5">位序 0（虚拟前驱）</text>
    <text class="fig-muted" x="227" y="162" text-anchor="middle" font-size="10.5">位序 1</text>
    <text class="fig-muted" x="345" y="162" text-anchor="middle" font-size="10.5">位序 2</text>
    <text class="fig-muted" x="463" y="162" text-anchor="middle" font-size="10.5">位序 n</text>
    <rect class="fig-box-subtle" x="18" y="182" width="644" height="90" rx="6"/>
    <line class="fig-line" stroke="var(--sl-color-orange)" x1="50" y1="234" x2="78" y2="234" marker-end="url(#wz-w1-arr-3)"/>
    <line class="fig-line" stroke="var(--sl-color-orange)" x1="168" y1="234" x2="196" y2="234" marker-end="url(#wz-w1-arr-3)"/>
    <line class="fig-line" stroke="var(--sl-color-orange)" x1="286" y1="234" x2="314" y2="234" marker-end="url(#wz-w1-arr-3)"/>
    <rect class="fig-box" x="80" y="216" width="88" height="36" rx="4"/>
    <line class="fig-divider" x1="138" y1="216" x2="138" y2="252"/>
    <rect class="fig-box" x="198" y="216" width="88" height="36" rx="4"/>
    <line class="fig-divider" x1="256" y1="216" x2="256" y2="252"/>
    <rect class="fig-box" x="316" y="216" width="88" height="36" rx="4"/>
    <line class="fig-divider" x1="374" y1="216" x2="374" y2="252"/>
    <rect class="fig-box-orange" x="444" y="216" width="204" height="36" rx="4"/>
    <text class="fig-title" x="32" y="203" font-size="12.5">不带头结点：L 直接指向首元 a₁，表头插入/删除必须单独修改头指针 L</text>
    <text class="fig-orange" x="38" y="238" text-anchor="middle" font-size="12.5">L</text>
    <text class="fig-label" x="109" y="238" text-anchor="middle" font-size="12">a₁(首元)</text>
    <circle class="fig-dot" cx="153" cy="234" r="2.8"/>
    <text class="fig-label" x="227" y="238" text-anchor="middle" font-size="12">a₂</text>
    <circle class="fig-dot" cx="271" cy="234" r="2.8"/>
    <text class="fig-label" x="345" y="238" text-anchor="middle" font-size="12">aₙ</text>
    <text class="fig-muted" x="389" y="238" text-anchor="middle" font-size="12">∧</text>
    <text class="fig-orange" x="546" y="238" text-anchor="middle" font-size="11.5">空表：L == NULL（无任何结点）</text>
  </svg>
  <figcaption>带头结点与不带头结点的单链表对比：头结点为首元提供前驱，消除空表与表头特判</figcaption>
</figure>

术语辨析：

| 术语 | 含义 |
| --- | --- |
| 头指针 | 指向链表中第一个结点（带头结点时即头结点）的指针，唯一标识整个链表，可用它命名链表 |
| 头结点 | 首元结点之前附加的结点，数据域不存数据元素（可空，也可存表长等），**不计入表长** |
| 首元结点 | 存放第一个数据元素 $a_1$ 的结点 |
| 空表 | 不带头结点：`L == NULL`；带头结点：`L->next == NULL` |

头结点的两点好处：① 首元结点与其余结点处理方式一致，插入删除不必特判表头；② 空表与非空表操作统一（判空只看 `L->next`）。

> **★考点**：链表是**顺序存取**（找第 $i$ 个必须从表头走 $i-1$ 步，$O(n)$），顺序表是**随机存取**（按下标 $O(1)$）。“顺序/链式”说的是存储方式，“随机/顺序”说的是存取方式，两组概念不可混。

### 单链表的类型定义

```c
typedef struct LNode {
    ElemType data;          // 数据域：类型由具体问题决定
    struct LNode *next;     // 指针域：指向同类型结点
} LNode, *LinkList;
```

- 结构体**自引用**：`next` 的类型是 `struct LNode *`，与正在定义的类型相同，用自己定义自己（嵌套定义）。
- `LNode` 是**结点类型**；`LinkList` 是**指向结点的指针类型**。
- 定义头指针用 `LinkList L;`（本身就是指针，不再加 `*`）；定义指向某结点的指针用 `LNode *p;`。两者等价写法均可，但习惯上表头用 `LinkList`、普通结点指针用 `LNode *`。

`data` 的类型随问题而变：多项式系数用 `float`，学生表则先定义结构类型：

```c
typedef struct {
    char no[8];
    char name[20];
    int  score;
} Student;

typedef struct LNode {
    Student data;
    struct LNode *next;
} LNode, *LinkList;
```

统一做法是**先把数据域的多个数据项定义成一个结构类型**，再以它作为 `data` 的类型，这样所有链表的操作都统一，不必为每种元素重写。

### 单链表的初始化、判空与求表长

**初始化**就是构造一个空的单链表：分配头结点，头指针指向它，指针域置空。

```c
Status InitList(LinkList &L) {
    L = new LNode;          // C 语言：L = (LinkList)malloc(sizeof(LNode));
    L->next = NULL;
    return OK;
}
```

$O(1)$。`new` 必须配 `delete`、`malloc` 必须配 `free`，不能混用。

**判空**：空表只有头结点，故只看头结点的指针域。

```c
int ListEmpty(LinkList L) {
    return L->next == NULL;   // 1 为空，0 为非空
}
```

$O(1)$。

**求表长**：从首元结点起逐个计数，头结点不计。

```c
int ListLength(LinkList L) {
    int i = 0;
    LNode *p = L->next;      // p 指向首元结点
    while (p) { ++i; p = p->next; }
    return i;
}
```

$O(n)$；空表时 `p` 一开始即为 `NULL`，返回 0。

三个必须背熟的基本动作：指向头结点 `p = L`；指向首元结点 `p = L->next`；后移一个结点 `p = p->next`。

### 单链表的销毁与清空

**销毁**：从表头起逐个释放，头结点也在内，链表彻底不存在（`L` 变为 `NULL`）。

```c
void DestroyList(LinkList &L) {
    LNode *p;
    while (L) {
        p = L;              // 暂存当前结点
        L = L->next;        // 先移头指针，否则后继地址丢失
        delete p;
    }
}
```

$O(n)$，结束条件 `L == NULL`。

**清空**：只释放首元结点起的元素结点，保留头指针与头结点，链表变为空表。

```c
void ClearList(LinkList &L) {
    LNode *p = L->next, *q;
    while (p) {
        q = p->next;        // 先记住下一个
        delete p;
        p = q;
    }
    L->next = NULL;         // 头结点指针域置空
}
```

$O(n)$。

> **注意**：循环里若写成 `p = q; q = q->next;`（先移 p）会漏掉一个结点；必须先取后继再释放，且指针移动顺序不可交换。
>
> **★考点**：销毁后 `L` 已不存在；清空后 `L->next == NULL`，`L` 仍指向头结点，表还可以继续使用。

<figure class="cpd-figure not-content" id="wz-w1-fig-7">
  <svg viewBox="0 0 680 236" role="img" aria-label="单链表销毁 DestroyList 与清空 ClearList 的内存释放范围对比">
    <defs>
      <marker id="wz-w1-arr-7d" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="18" y="14" width="318" height="206" rx="6"/>
    <rect class="fig-box-subtle" x="348" y="14" width="314" height="206" rx="6"/>
    <line class="fig-line-dashed" x1="120" y1="84" x2="146" y2="84" marker-end="url(#wz-w1-arr-7d)"/>
    <line class="fig-line-dashed" x1="224" y1="84" x2="250" y2="84" marker-end="url(#wz-w1-arr-7d)"/>
    <rect class="fig-box-red" x="42" y="66" width="78" height="36" rx="4"/>
    <rect class="fig-box-red" x="148" y="66" width="76" height="36" rx="4"/>
    <rect class="fig-box-red" x="252" y="66" width="68" height="36" rx="4"/>
    <rect class="fig-box" x="34" y="152" width="286" height="52" rx="5"/>
    <text class="fig-title" x="34" y="36" font-size="12.5">销毁 DestroyList(&amp;L)：连头结点一并释放</text>
    <text class="fig-red" x="81" y="88" text-anchor="middle" font-size="11.5">头 (delete)</text>
    <text class="fig-red" x="186" y="88" text-anchor="middle" font-size="11.5">a₁ (delete)</text>
    <text class="fig-red" x="286" y="88" text-anchor="middle" font-size="11.5">a₂ (delete)</text>
    <text class="fig-muted" x="177" y="128" text-anchor="middle" font-size="11">循环三步：p = L → L = L-&gt;next → delete p</text>
    <text class="fig-red" x="177" y="173" text-anchor="middle" font-size="11.5">结果：L == NULL（链表结构彻底消失）</text>
    <text class="fig-muted" x="177" y="193" text-anchor="middle" font-size="10.5">后续不可直接插入，需重新 InitList</text>
    <line class="fig-line-accent" x1="382" y1="84" x2="404" y2="84" marker-end="url(#wz-w1-arr-7d)"/>
    <line class="fig-line-dashed" x1="484" y1="84" x2="508" y2="84" marker-end="url(#wz-w1-arr-7d)"/>
    <line class="fig-line-dashed" x1="576" y1="84" x2="596" y2="84" marker-end="url(#wz-w1-arr-7d)"/>
    <rect class="fig-box-green" x="406" y="66" width="78" height="36" rx="4"/>
    <line class="fig-divider" x1="458" y1="66" x2="458" y2="102"/>
    <rect class="fig-box-orange" x="510" y="66" width="66" height="36" rx="4"/>
    <rect class="fig-box-orange" x="598" y="66" width="52" height="36" rx="4"/>
    <rect class="fig-box" x="362" y="152" width="286" height="52" rx="5"/>
    <text class="fig-title" x="362" y="36" font-size="12.5">清空 ClearList(&amp;L)：保留头结点，释放元素</text>
    <text class="fig-accent" x="370" y="88" text-anchor="middle" font-size="12">L</text>
    <text class="fig-green" x="432" y="88" text-anchor="middle" font-size="11.5">头保留</text>
    <text class="fig-green" x="471" y="88" text-anchor="middle" font-size="11.5">∧</text>
    <text class="fig-orange" x="543" y="88" text-anchor="middle" font-size="11">删 a₁(p)</text>
    <text class="fig-orange" x="624" y="88" text-anchor="middle" font-size="11">删 a₂(q)</text>
    <text class="fig-muted" x="505" y="128" text-anchor="middle" font-size="11">循环三步：q = p-&gt;next → delete p → p = q</text>
    <text class="fig-green" x="505" y="173" text-anchor="middle" font-size="11.5">结果：L-&gt;next == NULL（重置为空表）</text>
    <text class="fig-muted" x="505" y="193" text-anchor="middle" font-size="10.5">头结点仍在内存，表可直接继续插入元素</text>
  </svg>
  <figcaption>单链表销毁与清空对比：释放前必须先暂存后继地址，防止断链内存泄漏</figcaption>
</figure>

### 取第 i 个元素与按值查找

链表不能按下标直接定位，只能从首元结点顺链扫描，用计数器 $j$ 记录走到第几个结点。

```c
Status GetElem(LinkList L, int i, ElemType &e) {
    LNode *p = L->next;
    int j = 1;
    while (p && j < i) { p = p->next; ++j; }
    if (!p || j > i) return ERROR;   // i<1 或 i>表长
    e = p->data;
    return OK;
}
```

$O(n)$。两类非法位置：$i<1$ 时循环体不执行，靠 `j > i` 判出；$i>$ 表长时 `p` 走到 `NULL`，靠 `!p` 判出。

**按值查找**返回结点地址：

```c
LNode *LocateElem(LinkList L, ElemType e) {
    LNode *p = L->next;
    while (p && p->data != e) p = p->next;
    return p;           // 找到返回结点指针，否则 NULL
}
```

若要求返回**序号**，另设计数器 `j`：找到返回 `j`，遍历完仍未找到返回 0。

```c
int LocateElem_Sq(LinkList L, ElemType e) {
    LNode *p = L->next; int j = 1;
    while (p && p->data != e) { p = p->next; ++j; }
    return p ? j : 0;
}
```

$O(n)$：最好情况第 1 个即命中，最坏第 $n$ 个，平均仍为 $O(n)$。

### 单链表的插入与删除

**插入**：在第 $i$ 个结点之前插入值为 $e$ 的新结点。先找第 $i-1$ 个结点 $p$，再改两根指针。

```c
Status ListInsert(LinkList &L, int i, ElemType e) {
    LNode *p = L, *s;
    int j = 0;
    while (p && j < i - 1) { p = p->next; ++j; }   // 找第 i-1 个结点
    if (!p || j > i - 1) return ERROR;             // i<1 或 i>表长+1
    s = new LNode;
    s->data = e;
    s->next = p->next;      // ① 新结点先接原 ai
    p->next = s;            // ② 前驱再接新结点
    return OK;
}
```

**过程拆解**（在 `p` 之后插入 `s`）：

| 步骤 | 指针动作 | 链表状态 |
|:---:|:---|:---|
| 初始 | `p` 指向 `a1`，`s` 指向新结点 `e` | `L → a1 → a2 → …` |
| ① | `s->next = p->next` | `s` 指向 `a2`，`p` 仍指向 `a2` |
| ② | `p->next = s` | `L → a1 → s → a2 → …` |

删除 `p` 的后继 `q`：

| 步骤 | 指针动作 | 链表状态 |
|:---:|:---|:---|
| 初始 | `q = p->next` | `p → q → q->next` |
| ① | `p->next = q->next` | `p` 直接指向 `q` 的后继 |
| ② | `free(q)` | `q` 被释放，链表跳过 `q` |

> **注意**：插入的 ①② 不能交换；删除必须先保存 `q`，否则无法释放结点和取回元素值。

**删除**：删除第 $i$ 个结点，让它的前驱直接指向它的后继。

```c
Status ListDelete(LinkList &L, int i, ElemType &e) {
    LNode *p = L, *q;
    int j = 0;
    while (p->next && j < i - 1) { p = p->next; ++j; }
    if (!(p->next) || j > i - 1) return ERROR;
    q = p->next;            // q 指向待删结点（保存以便释放和取值）
    p->next = q->next;      // 摘链：前驱指向后继
    e = q->data;
    delete q;
    return OK;
}
```

核心一步可写成 `p->next = p->next->next`，但必须先保存被删结点地址，否则无法 `delete` 与取回元素值。

定位循环的边界略有差别：插入用 `while (p && ...)`（$p$ 可为最后一个结点，插在表尾之后），删除用 `while (p->next && ...)`（$p$ 必须真有后继可删）。

**复杂度**：查找 $O(n)$；指针修改本身 $O(1)$。整体插入/删除为 $O(n)$（因需先定位），但**不移动元素**——这与顺序表平均移动约 $n/2$ 个元素形成对比，是链表的核心优势。

<figure class="cpd-figure not-content" id="wz-fig-4">
  <svg viewBox="0 0 680 310" role="img" aria-label="单链表结点插入两步先连后断与删除摘链指针操作对比">
    <defs>
      <marker id="wz-w1-arr-4" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="18" y="14" width="644" height="142" rx="6"/>
    <path class="fig-line-dashed" d="M 154 78 C 210 42, 410 42, 466 78" marker-end="url(#wz-w1-arr-4)"/>
    <line class="fig-line-accent" x1="358" y1="88" x2="466" y2="88" marker-end="url(#wz-w1-arr-4)"/>
    <line class="fig-line" stroke="var(--sl-color-green)" x1="154" y1="98" x2="254" y2="98" marker-end="url(#wz-w1-arr-4)"/>
    <rect class="fig-box" x="48" y="68" width="106" height="40" rx="4"/>
    <line class="fig-divider" x1="118" y1="68" x2="118" y2="108"/>
    <rect class="fig-box-accent" x="256" y="68" width="102" height="40" rx="4"/>
    <line class="fig-divider" x1="322" y1="68" x2="322" y2="108"/>
    <rect class="fig-box" x="468" y="68" width="106" height="40" rx="4"/>
    <line class="fig-divider" x1="538" y1="68" x2="538" y2="108"/>
    <rect class="fig-box" x="240" y="38" width="140" height="18" rx="3"/>
    <rect class="fig-box" x="342" y="66" width="140" height="17" rx="3"/>
    <text class="fig-title" x="32" y="34" font-size="12.5">插入（在 p 后插 s）：① 先连 s-&gt;next = p-&gt;next　→　② 后改 p-&gt;next = s</text>
    <text class="fig-muted" x="310" y="52" text-anchor="middle" font-size="11">原 p-&gt;next（步②后断开）</text>
    <text class="fig-label" x="83" y="92" text-anchor="middle" font-size="12">aᵢ₋₁ (p)</text>
    <circle class="fig-dot" cx="136" cy="88" r="3"/>
    <text class="fig-accent" x="289" y="92" text-anchor="middle" font-size="12">e (s)</text>
    <circle class="fig-dot" cx="340" cy="88" r="3"/>
    <text class="fig-label" x="503" y="92" text-anchor="middle" font-size="12">aᵢ</text>
    <text class="fig-muted" x="556" y="92" text-anchor="middle" font-size="12">…</text>
    <text class="fig-accent" x="412" y="80" text-anchor="middle" font-size="11.5">① s-&gt;next = p-&gt;next</text>
    <text class="fig-green" x="204" y="118" text-anchor="middle" font-size="11.5">② p-&gt;next = s</text>
    <text class="fig-red" x="340" y="142" text-anchor="middle" font-size="11">严禁颠倒：若先写 p-&gt;next = s，原后继 aᵢ 的地址立即丢失导致断链！</text>
    <rect class="fig-box-subtle" x="18" y="166" width="644" height="130" rx="6"/>
    <line class="fig-line-dashed" x1="154" y1="234" x2="254" y2="234" marker-end="url(#wz-w1-arr-4)"/>
    <line class="fig-line-dashed" x1="358" y1="234" x2="466" y2="234" marker-end="url(#wz-w1-arr-4)"/>
    <path class="fig-line-accent" d="M 136 214 C 210 184, 410 184, 466 218" marker-end="url(#wz-w1-arr-4)"/>
    <rect class="fig-box" x="48" y="214" width="106" height="40" rx="4"/>
    <line class="fig-divider" x1="118" y1="214" x2="118" y2="254"/>
    <rect class="fig-box-orange" x="256" y="214" width="102" height="40" rx="4"/>
    <line class="fig-divider" x1="322" y1="214" x2="322" y2="254"/>
    <rect class="fig-box" x="468" y="214" width="106" height="40" rx="4"/>
    <line class="fig-divider" x1="538" y1="214" x2="538" y2="254"/>
    <rect class="fig-box" x="204" y="185" width="212" height="18" rx="3"/>
    <text class="fig-title" x="32" y="186" font-size="12.5">删除（删 p 后继 q）：① q = p-&gt;next 保存　→　② p-&gt;next = q-&gt;next 摘链　→　③ delete q</text>
    <text class="fig-accent" x="310" y="198" text-anchor="middle" font-size="11.5">② p-&gt;next = q-&gt;next（跨过 q）</text>
    <text class="fig-label" x="83" y="238" text-anchor="middle" font-size="12">aᵢ₋₁ (p)</text>
    <circle class="fig-dot" cx="136" cy="234" r="3"/>
    <text class="fig-orange" x="289" y="238" text-anchor="middle" font-size="12">aᵢ (q)</text>
    <circle class="fig-dot-muted" cx="340" cy="234" r="3"/>
    <text class="fig-label" x="503" y="238" text-anchor="middle" font-size="12">aᵢ₊₁</text>
    <text class="fig-muted" x="556" y="238" text-anchor="middle" font-size="12">…</text>
    <text class="fig-muted" x="340" y="280" text-anchor="middle" font-size="11">定位边界差异：插入循环判 p（可插表尾后），删除循环判 p-&gt;next（必须真有后继结点可删）</text>
  </svg>
  <figcaption>单链表插入（先连后改两根指针）与删除（暂存 q、摘链、释放）的完整指针机制</figcaption>
</figure>

### 头插法与尾插法建立单链表

**头插法**（前插法）：从空表开始，每读入一个数据就插到头结点之后。要得到正序链表，必须**逆序读入**（先 $a_n$，最后 $a_1$）。

```c
void CreateList_H(LinkList &L, int n) {
    L = new LNode;
    L->next = NULL;                 // 空表
    for (int i = 0; i < n; ++i) {
        LNode *p = new LNode;
        cin >> p->data;             // C: scanf("%d", &p->data);
        p->next = L->next;          // 原有首元链接到新结点之后
        L->next = p;                // 新结点接到头结点之后
    }
}
```

两步的实质：**把原表整串挂到新结点后面，再把新结点挂到头结点后面**。$O(n)$，结果与输入顺序相反。

**尾插法**（后插法）：增设尾指针 `r` 始终指向最后一个结点，正序读入。

```c
void CreateList_R(LinkList &L, int n) {
    L = new LNode;
    L->next = NULL;
    LNode *r = L;                   // 初始时尾指针指向头结点
    for (int i = 0; i < n; ++i) {
        LNode *p = new LNode;
        cin >> p->data;
        p->next = NULL;             // 新结点将成为表尾
        r->next = p;                // 接到表尾
        r = p;                       // 尾指针后移
    }
}
```

$O(n)$，结果与输入顺序一致。

| 比较项 | 头插法 | 尾插法 |
| --- | --- | --- |
| 插入位置 | 头结点之后（表头） | 尾结点之后（表尾） |
| 读入次序 | 逆序（$a_n \to a_1$） | 正序（$a_1 \to a_n$） |
| 额外指针 | 不需要 | 需要尾指针 `r` |
| 结果顺序 | 与输入相反 | 与输入相同 |
| 时间复杂度 | $O(n)$ | $O(n)$ |

> **注意**：头插法建表后，若题目要求“输入顺序即表顺序”，必须逆序输入或建完后再逆置；尾插法天然保持顺序。

<figure class="cpd-figure not-content" id="wz-w1-fig-8">
  <svg viewBox="0 0 680 278" role="img" aria-label="头插法与尾插法建立单链表的指针变化与最终序列顺序对比">
    <defs>
      <marker id="wz-w1-arr-8h" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="18" y="14" width="644" height="120" rx="6"/>
    <line class="fig-line-accent" x1="52" y1="82" x2="78" y2="82" marker-end="url(#wz-w1-arr-8h)"/>
    <line class="fig-line-accent" x1="158" y1="82" x2="198" y2="82" marker-end="url(#wz-w1-arr-8h)"/>
    <line class="fig-line-accent" x1="278" y1="82" x2="318" y2="82" marker-end="url(#wz-w1-arr-8h)"/>
    <line class="fig-line" x1="398" y1="82" x2="438" y2="82" marker-end="url(#wz-w1-arr-8h)"/>
    <rect class="fig-box-purple" x="80" y="64" width="78" height="36" rx="4"/>
    <line class="fig-divider" x1="132" y1="64" x2="132" y2="100"/>
    <rect class="fig-box-accent" x="200" y="64" width="78" height="36" rx="4"/>
    <line class="fig-divider" x1="252" y1="64" x2="252" y2="100"/>
    <rect class="fig-box" x="320" y="64" width="78" height="36" rx="4"/>
    <line class="fig-divider" x1="372" y1="64" x2="372" y2="100"/>
    <rect class="fig-box" x="440" y="64" width="78" height="36" rx="4"/>
    <line class="fig-divider" x1="492" y1="64" x2="492" y2="100"/>
    <rect class="fig-box-orange" x="534" y="54" width="114" height="56" rx="5"/>
    <text class="fig-title" x="32" y="36" font-size="12.5">头插法 CreateList_H（依次输入 10, 20, 30）：每次插在头结点之后</text>
    <text class="fig-muted" x="178" y="54" text-anchor="middle" font-size="10.5">② L-&gt;next = p</text>
    <text class="fig-muted" x="298" y="54" text-anchor="middle" font-size="10.5">① p-&gt;next = L-&gt;next</text>
    <text class="fig-accent" x="40" y="86" text-anchor="middle" font-size="12">L</text>
    <text class="fig-purple" x="106" y="86" text-anchor="middle" font-size="11.5">头结点</text>
    <circle class="fig-dot" cx="145" cy="82" r="2.8"/>
    <text class="fig-accent" x="226" y="86" text-anchor="middle" font-size="12">30(p)</text>
    <circle class="fig-dot" cx="265" cy="82" r="2.8"/>
    <text class="fig-label" x="346" y="86" text-anchor="middle" font-size="12">20</text>
    <circle class="fig-dot" cx="385" cy="82" r="2.8"/>
    <text class="fig-label" x="466" y="86" text-anchor="middle" font-size="12">10</text>
    <text class="fig-muted" x="505" y="86" text-anchor="middle" font-size="12">∧</text>
    <text class="fig-orange" x="591" y="78" text-anchor="middle" font-size="11.5">结果与输入逆序</text>
    <text class="fig-muted" x="591" y="96" text-anchor="middle" font-size="10.5">常用于链表原地逆置</text>
    <rect class="fig-box-subtle" x="18" y="144" width="644" height="120" rx="6"/>
    <line class="fig-line" x1="52" y1="208" x2="78" y2="208" marker-end="url(#wz-w1-arr-8h)"/>
    <line class="fig-line" x1="158" y1="208" x2="198" y2="208" marker-end="url(#wz-w1-arr-8h)"/>
    <line class="fig-line" x1="278" y1="208" x2="318" y2="208" marker-end="url(#wz-w1-arr-8h)"/>
    <line class="fig-line-accent" x1="398" y1="208" x2="438" y2="208" marker-end="url(#wz-w1-arr-8h)"/>
    <line class="fig-line-accent" x1="479" y1="252" x2="479" y2="230" marker-end="url(#wz-w1-arr-8h)"/>
    <rect class="fig-box-purple" x="80" y="190" width="78" height="36" rx="4"/>
    <line class="fig-divider" x1="132" y1="190" x2="132" y2="226"/>
    <rect class="fig-box" x="200" y="190" width="78" height="36" rx="4"/>
    <line class="fig-divider" x1="252" y1="190" x2="252" y2="226"/>
    <rect class="fig-box" x="320" y="190" width="78" height="36" rx="4"/>
    <line class="fig-divider" x1="372" y1="190" x2="372" y2="226"/>
    <rect class="fig-box-green" x="440" y="190" width="78" height="36" rx="4"/>
    <line class="fig-divider" x1="492" y1="190" x2="492" y2="226"/>
    <rect class="fig-box-green" x="534" y="180" width="114" height="56" rx="5"/>
    <text class="fig-title" x="32" y="166" font-size="12.5">尾插法 CreateList_R（依次输入 10, 20, 30）：尾指针 r 始终指向当前终端结点</text>
    <text class="fig-accent" x="418" y="182" text-anchor="middle" font-size="10.5">① r-&gt;next = p</text>
    <text class="fig-label" x="40" y="212" text-anchor="middle" font-size="12">L</text>
    <text class="fig-purple" x="106" y="212" text-anchor="middle" font-size="11.5">头结点</text>
    <circle class="fig-dot" cx="145" cy="208" r="2.8"/>
    <text class="fig-label" x="226" y="212" text-anchor="middle" font-size="12">10</text>
    <circle class="fig-dot" cx="265" cy="208" r="2.8"/>
    <text class="fig-label" x="346" y="212" text-anchor="middle" font-size="12">20</text>
    <circle class="fig-dot" cx="385" cy="208" r="2.8"/>
    <text class="fig-green" x="466" y="212" text-anchor="middle" font-size="12">30(p)</text>
    <text class="fig-muted" x="505" y="212" text-anchor="middle" font-size="12">∧</text>
    <text class="fig-accent" x="470" y="256" text-anchor="end" font-size="11">② r = p（尾指针后移）</text>
    <text class="fig-green" x="591" y="204" text-anchor="middle" font-size="11.5">结果与输入同序</text>
    <text class="fig-muted" x="591" y="222" text-anchor="middle" font-size="10.5">时间同为 O(n)</text>
  </svg>
  <figcaption>头插法（无需尾指针、序列逆置）与尾插法（需尾指针 r、保持原序）建表对比</figcaption>
</figure>

> **交互演示**：[单链表建表与插入删除](/lab/chapter-2/#lab-headInsert)

### 循环链表

将单链表尾结点的指针域由空改为指向**头结点**（或首元结点），首尾相接，即循环链表。好处是从任一结点出发都能遍历全表，不存在“走到头就停”的死角。

带头指针的循环链表：找 $a_1$ 为 $O(1)$（`L->next`），找 $a_n$ 需绕一圈 $O(n)$。

带**尾指针** `r` 的循环单链表：`r` 指向 $a_n$，`r->next` 是头结点，`r->next->next` 是 $a_1$。找表头、表尾都是 $O(1)$，因此首尾操作频繁时优先用尾指针表示。

> **★考点**：循环链表中**没有空指针**，遍历终止条件不再是 `p == NULL` 或 `p->next == NULL`，而是 `p != L`（或 `p->next != L`）。沿用单链表的判空条件会死循环。

两个带尾指针的循环链表合并（`Ta`、`Tb` 分别指向两表尾结点，结果用 `Tb` 表示）：

```c
p = Ta->next;                  // ① 先保存 Ta 的头结点地址
Ta->next = Tb->next->next;     // ② Tb 的首元结点接到 Ta 表尾
delete Tb->next;               // ③ 释放 Tb 多余的头结点
Tb->next = p;                  // ④ Tb 尾结点指向 Ta 头结点
return Tb;
```

$O(1)$：只改三根指针、删一个结点，与表长无关。

> **注意**：① 必须最先做。② 一旦执行，`Ta->next` 已被覆盖，再也找不到 Ta 的头结点；③ 之后再想取 `Tb->next` 也已失效。

<figure class="cpd-figure not-content" id="wz-fig-5">
  <svg viewBox="0 0 680 306" role="img" aria-label="带尾指针的循环单链表结构与两循环链表四步 O(1) 合并过程">
    <defs>
      <marker id="wz-w1-arr-5" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="18" y="14" width="644" height="128" rx="6"/>
    <line class="fig-line-accent" x1="130" y1="88" x2="188" y2="88" marker-end="url(#wz-w1-arr-5)"/>
    <line class="fig-line-accent" x1="272" y1="88" x2="330" y2="88" marker-end="url(#wz-w1-arr-5)"/>
    <line class="fig-line-accent" x1="414" y1="88" x2="472" y2="88" marker-end="url(#wz-w1-arr-5)"/>
    <polyline class="fig-line-accent" points="558,88 594,88 594,46 88,46 88,68" marker-end="url(#wz-w1-arr-5)"/>
    <line class="fig-line-accent" x1="636" y1="118" x2="560" y2="100" marker-end="url(#wz-w1-arr-5)"/>
    <rect class="fig-box-purple" x="46" y="70" width="84" height="36" rx="4"/>
    <rect class="fig-box" x="190" y="70" width="82" height="36" rx="4"/>
    <rect class="fig-box" x="332" y="70" width="82" height="36" rx="4"/>
    <rect class="fig-box-accent" x="474" y="70" width="84" height="36" rx="4"/>
    <text class="fig-title" x="32" y="34" font-size="12.5">带尾指针 r 的循环单链表：表尾 r、表头 r-&gt;next、首元 r-&gt;next-&gt;next 均为 O(1)</text>
    <text class="fig-purple" x="88" y="92" text-anchor="middle" font-size="11.5">头 (r-&gt;next)</text>
    <text class="fig-label" x="231" y="92" text-anchor="middle" font-size="12">a₁ (首元)</text>
    <text class="fig-label" x="373" y="92" text-anchor="middle" font-size="12">a₂</text>
    <text class="fig-accent" x="516" y="92" text-anchor="middle" font-size="12">aₙ (表尾)</text>
    <text class="fig-accent" x="634" y="130" text-anchor="middle" font-size="11.5">尾指针 r</text>
    <text class="fig-muted" x="300" y="128" text-anchor="middle" font-size="11">遍历终止条件：p != L（或 p-&gt;next != L），切勿判 NULL 防死循环</text>
    <rect class="fig-box-subtle" x="18" y="152" width="644" height="140" rx="6"/>
    <line class="fig-line" x1="108" y1="224" x2="146" y2="224" marker-end="url(#wz-w1-arr-5)"/>
    <line class="fig-line" x1="216" y1="224" x2="254" y2="224" marker-end="url(#wz-w1-arr-5)"/>
    <line class="fig-line-accent" x1="324" y1="224" x2="432" y2="224" marker-end="url(#wz-w1-arr-5)"/>
    <line class="fig-line" x1="502" y1="224" x2="540" y2="224" marker-end="url(#wz-w1-arr-5)"/>
    <polyline class="fig-line" stroke="var(--sl-color-green)" points="610,224 638,224 638,268 73,268 73,244" marker-end="url(#wz-w1-arr-5)"/>
    <rect class="fig-box-purple" x="38" y="206" width="70" height="36" rx="4"/>
    <rect class="fig-box" x="148" y="206" width="68" height="36" rx="4"/>
    <rect class="fig-box-blue" x="256" y="206" width="68" height="36" rx="4"/>
    <rect class="fig-box-orange" x="342" y="176" width="74" height="28" rx="4"/>
    <rect class="fig-box" x="434" y="206" width="68" height="36" rx="4"/>
    <rect class="fig-box-green" x="542" y="206" width="68" height="36" rx="4"/>
    <text class="fig-title" x="32" y="172" font-size="12.5">两循环链表 Ta、Tb 合并为 Tb（O(1) 时间，仅改指针不扫描全表）</text>
    <text class="fig-purple" x="73" y="228" text-anchor="middle" font-size="11">① 存 p</text>
    <text class="fig-label" x="182" y="228" text-anchor="middle" font-size="11.5">a₁…</text>
    <text class="fig-blue" x="290" y="228" text-anchor="middle" font-size="11.5">aₘ(Ta)</text>
    <text class="fig-orange" x="379" y="194" text-anchor="middle" font-size="10.5">③ 删 Tb 头</text>
    <text class="fig-accent" x="379" y="218" text-anchor="middle" font-size="10.5">② Ta-&gt;next 接 b₁</text>
    <text class="fig-label" x="468" y="228" text-anchor="middle" font-size="11.5">b₁…</text>
    <text class="fig-green" x="576" y="228" text-anchor="middle" font-size="11.5">bₙ(Tb)</text>
    <text class="fig-green" x="355" y="284" text-anchor="middle" font-size="11">④ Tb-&gt;next = p（新表尾 Tb 指回原 Ta 头结点 p，合并完成）</text>
  </svg>
  <figcaption>循环单链表尾指针表示法及两表四步 O(1) 合并：① 存 p → ② 接 b₁ → ③ 删 Tb 头 → ④ 闭环</figcaption>
</figure>

### 双向链表

单链表找前驱必须从头扫描（$O(n)$）。双向链表在每个结点中**再增加一个指向前驱的指针域** `prior`，结点变为三域：

```c
typedef struct DuLNode {
    ElemType data;
    struct DuLNode *prior;      // 指向前驱
    struct DuLNode *next;       // 指向后继
} DuLNode, *DuLinkList;
```

非循环双向链表：尾结点 `next` 为空、首元结点 `prior` 为空；空表时头结点的 `next` 与 `prior` 均为空。双向循环链表：尾结点 `next` 指向头结点，头结点 `prior` 指向尾结点；空表时头结点的两个指针都指向自身。

**对称性**：对任一结点 `p`，有

$$
p \rightarrow \text{prior} \rightarrow \text{next} = p = p \rightarrow \text{next} \rightarrow \text{prior}
$$

求表长、取第 $i$ 个元素只沿一条链走即可，算法与单链表完全相同；只有插入、删除需要同时维护两个方向。

**插入**：在 `p` 所指结点之前插入 `s`。

```c
s->prior = p->prior;        // ① s 的前驱 = a
p->prior->next = s;         // ② a 的后继 = s
s->next = p;                // ③ s 的后继 = b（即 p）
p->prior = s;               // ④ b 的前驱 = s
```

共修改 **4 个指针**（单链表插入只需 2 个）。①必须在④之前，因为④会改写 `p->prior`；除此之外四步都操作各自独立的域，先后可调。

**删除** `p` 所指结点：

```c
p->prior->next = p->next;      // ① 前驱的后继 = 后继
p->next->prior = p->prior;     // ② 后继的前驱 = 前驱
delete p;
```

只改 **2 个指针**，且**不需要再找前驱**——这是双向链表相对单链表的关键优势：已知 `p` 时删除为 $O(1)$；若需按序号先定位 `p`，仍为 $O(n)$。

<figure class="cpd-figure not-content" id="wz-fig-6">
  <svg viewBox="0 0 680 318" role="img" aria-label="双向链表四步指针插入与两步指针 O(1) 删除过程对比">
    <defs>
      <marker id="wz-w1-arr-6" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="18" y="14" width="644" height="150" rx="6"/>
    <line class="fig-line" stroke="var(--sl-color-blue)" x1="274" y1="84" x2="170" y2="84" marker-end="url(#wz-w1-arr-6)"/>
    <line class="fig-line" stroke="var(--sl-color-blue)" x1="406" y1="84" x2="510" y2="84" marker-end="url(#wz-w1-arr-6)"/>
    <line class="fig-line" stroke="var(--sl-color-green)" x1="168" y1="110" x2="272" y2="110" marker-end="url(#wz-w1-arr-6)"/>
    <line class="fig-line" stroke="var(--sl-color-green)" x1="512" y1="110" x2="408" y2="110" marker-end="url(#wz-w1-arr-6)"/>
    <rect class="fig-box" x="36" y="68" width="132" height="56" rx="4"/>
    <line class="fig-divider" x1="78" y1="68" x2="78" y2="124"/>
    <line class="fig-divider" x1="126" y1="68" x2="126" y2="124"/>
    <rect class="fig-box-accent" x="274" y="68" width="132" height="56" rx="4"/>
    <line class="fig-divider" x1="316" y1="68" x2="316" y2="124"/>
    <line class="fig-divider" x1="364" y1="68" x2="364" y2="124"/>
    <rect class="fig-box" x="512" y="68" width="132" height="56" rx="4"/>
    <line class="fig-divider" x1="554" y1="68" x2="554" y2="124"/>
    <line class="fig-divider" x1="602" y1="68" x2="602" y2="124"/>
    <text class="fig-title" x="34" y="34" font-size="12.5">双向链表插入（在 p 后插 s，q = p-&gt;next）：共改 4 根指针（先挂好 s，再改 p 与 q）</text>
    <text class="fig-blue" x="221" y="58" text-anchor="middle" font-size="11.5">① s-&gt;prior = p</text>
    <text class="fig-blue" x="459" y="58" text-anchor="middle" font-size="11.5">② s-&gt;next = q</text>
    <text class="fig-muted" x="57" y="100" text-anchor="middle" font-size="11">prior</text>
    <text class="fig-label" x="102" y="100" text-anchor="middle" font-size="11.5">aᵢ (p)</text>
    <text class="fig-muted" x="147" y="100" text-anchor="middle" font-size="11">next</text>
    <text class="fig-muted" x="295" y="100" text-anchor="middle" font-size="11">prior</text>
    <text class="fig-accent" x="340" y="100" text-anchor="middle" font-size="11.5">e (s)</text>
    <text class="fig-muted" x="385" y="100" text-anchor="middle" font-size="11">next</text>
    <text class="fig-muted" x="533" y="100" text-anchor="middle" font-size="11">prior</text>
    <text class="fig-label" x="578" y="100" text-anchor="middle" font-size="11.5">aᵢ₊₁(q)</text>
    <text class="fig-muted" x="623" y="100" text-anchor="middle" font-size="11">next</text>
    <text class="fig-green" x="221" y="146" text-anchor="middle" font-size="11.5">③ p-&gt;next = s</text>
    <text class="fig-green" x="459" y="146" text-anchor="middle" font-size="11.5">④ q-&gt;prior = s（q 非空）</text>
    <rect class="fig-box-subtle" x="18" y="174" width="644" height="130" rx="6"/>
    <path class="fig-line-accent" d="M 147 216 C 230 198, 450 198, 512 222" marker-end="url(#wz-w1-arr-6)"/>
    <path class="fig-line" stroke="var(--sl-color-green)" d="M 533 268 C 450 296, 230 296, 168 260" marker-end="url(#wz-w1-arr-6)"/>
    <rect class="fig-box" x="36" y="216" width="132" height="52" rx="4"/>
    <line class="fig-divider" x1="78" y1="216" x2="78" y2="268"/>
    <line class="fig-divider" x1="126" y1="216" x2="126" y2="268"/>
    <rect class="fig-box-orange" x="274" y="216" width="132" height="52" rx="4"/>
    <line class="fig-divider" x1="316" y1="216" x2="316" y2="268"/>
    <line class="fig-divider" x1="364" y1="216" x2="364" y2="268"/>
    <rect class="fig-box" x="512" y="216" width="132" height="52" rx="4"/>
    <line class="fig-divider" x1="554" y1="216" x2="554" y2="268"/>
    <line class="fig-divider" x1="602" y1="216" x2="602" y2="268"/>
    <rect class="fig-box" x="244" y="196" width="192" height="16" rx="3"/>
    <rect class="fig-box" x="256" y="281" width="168" height="17" rx="3"/>
    <text class="fig-title" x="34" y="194" font-size="12.5">双向链表删除结点 p：直接由 p-&gt;prior 找前驱，改 2 根指针即完成 O(1) 摘链</text>
    <text class="fig-accent" x="340" y="208" text-anchor="middle" font-size="11">① p-&gt;prior-&gt;next = p-&gt;next</text>
    <text class="fig-label" x="102" y="246" text-anchor="middle" font-size="11.5">p-&gt;prior</text>
    <text class="fig-orange" x="340" y="246" text-anchor="middle" font-size="11.5">delete p</text>
    <text class="fig-label" x="578" y="246" text-anchor="middle" font-size="11.5">p-&gt;next</text>
    <text class="fig-green" x="340" y="294" text-anchor="middle" font-size="11">② p-&gt;next-&gt;prior = p-&gt;prior</text>
  </svg>
  <figcaption>双向链表插入（改 4 根指针）与删除（直接找前驱改 2 根指针，已知结点 p 时 O(1)）对比</figcaption>
</figure>

**过程拆解**（在 `p` 之后插入 `s`，`q = p->next`）：

| 步骤 | 指针动作 | 说明 |
|:---:|:---|:---|
| ① | `s->prior = p` | 新结点先指向前驱 |
| ② | `s->next = q` | 新结点指向后继 |
| ③ | `p->next = s` | 前驱改指新结点 |
| ④ | `q->prior = s` | 后继改指新结点（`q` 非空时） |

若 `q` 为空（插在表尾）：只做 ①②③，并令 `s->next = NULL`，不需要第 ④ 步。

> **交互演示**：[双向链表与循环链表](/lab/chapter-2/#lab-doublyList)

### 三种链表的比较

| 操作 | 带头结点单链表 | 循环单链表（头指针） | 循环单链表（尾指针 `r`） | 双向循环链表 |
| --- | --- | --- | --- | --- |
| 找首元 $a_1$ | $O(1)$ `L->next` | $O(1)$ `L->next` | $O(1)$ `r->next->next` | $O(1)$ `L->next` |
| 找表尾 $a_n$ | $O(n)$ 顺链扫描 | $O(n)$ 顺链扫描 | $O(1)$ `r` | $O(1)$ `L->prior` |
| 找 `p` 的前驱 | 不能由 `p` 得到，需从头 $O(n)$ | $O(n)$ 绕一圈 | $O(n)$ 绕一圈 | $O(1)$ `p->prior` |

**选型结论**：经常操作表尾 → 带尾指针的循环单链表；经常找前驱或双向遍历 → 双向链表；只需单向顺序访问、节省空间 → 普通单链表。

双向循环链表三种操作都是 $O(1)$，但它为每个结点多存一个指针域——本质是**以空间换时间**，不能只看时间复杂度就断定它最优。

### 顺序表与链表的比较

链式存储的优缺点：

- **优**：空间动态申请、按需释放，不必预分配大块连续空间；插入删除只改指针，不移动元素。
- **缺**：每个结点要额外存指针，**存储密度小于 1**；不能随机存取，按序号访问为 $O(n)$。

存储密度定义为数据域占用空间与结点总占用空间之比：

$$
\text{存储密度} = \frac{\text{数据域占用空间}}{\text{结点占用总空间}}
$$

例如数据占 8 字节、指针占 4 字节，则 $8/(8+4)\approx 0.67$；顺序表只存数据本身，存储密度为 1。

| 比较项 | 顺序表 | 链表 |
| --- | --- | --- |
| 空间分配 | 预先分配固定大小，可能溢出或闲置浪费 | 动态分配，需要时申请、不用时释放 |
| 存储密度 | 1 | 小于 1（含指针域） |
| 存取方式 | 随机存取，按序号 $O(1)$ | 顺序存取，按序号 $O(n)$ |
| 插入/删除 | 平均移动约 $n/2$ 个元素，$O(n)$ | 修改指针 $O(1)$（不含定位） |
| 逻辑相邻与物理相邻 | 一致 | 不一致，靠指针表达 |
| 适用场景 | 表长变化小且可预估、常按序号访问 | 表长变化大、频繁插入删除 |

结论：两者没有绝对优劣。按“表长是否稳定 + 主要操作是访问还是增删”选择，是本章应用题的通用判据。

<figure class="cpd-figure not-content" id="wz-w1-fig-9">
  <svg viewBox="0 0 680 232" role="img" aria-label="顺序表、单链表与双链表的存储密度对比及选型判据">
    <rect class="fig-box-subtle" x="18" y="14" width="332" height="202" rx="6"/>
    <rect class="fig-box-subtle" x="362" y="14" width="300" height="202" rx="6"/>
    <rect class="fig-box-green" x="116" y="48" width="160" height="32" rx="4"/>
    <rect class="fig-box-blue" x="116" y="96" width="160" height="32" rx="4"/>
    <rect class="fig-box-purple" x="276" y="96" width="60" height="32" rx="4"/>
    <rect class="fig-box-purple" x="116" y="144" width="54" height="32" rx="4"/>
    <rect class="fig-box-blue" x="170" y="144" width="112" height="32" rx="4"/>
    <rect class="fig-box-purple" x="282" y="144" width="54" height="32" rx="4"/>
    <text class="fig-title" x="32" y="34" font-size="12.5">存储密度对比（设 data = 8B，指针 = 4B）</text>
    <text class="fig-label" x="32" y="68" font-size="11.5">顺序表</text>
    <text class="fig-green" x="196" y="68" text-anchor="middle" font-size="11.5">data (8B) → 密度 = 100%</text>
    <text class="fig-label" x="32" y="116" font-size="11.5">单链表</text>
    <text class="fig-blue" x="196" y="116" text-anchor="middle" font-size="11.5">data (8B)</text>
    <text class="fig-purple" x="306" y="116" text-anchor="middle" font-size="11">next(4B)</text>
    <text class="fig-label" x="32" y="164" font-size="11.5">双链表</text>
    <text class="fig-purple" x="143" y="164" text-anchor="middle" font-size="10.5">prior</text>
    <text class="fig-blue" x="226" y="164" text-anchor="middle" font-size="11.5">data (8B)</text>
    <text class="fig-purple" x="309" y="164" text-anchor="middle" font-size="10.5">next</text>
    <text class="fig-muted" x="184" y="198" text-anchor="middle" font-size="11">单链表 8/12 ≈ 0.67；双链表 8/16 = 0.50（空间换时间）</text>
    <rect class="fig-box-accent" x="376" y="48" width="272" height="72" rx="5"/>
    <rect class="fig-box-orange" x="376" y="132" width="272" height="70" rx="5"/>
    <text class="fig-title" x="376" y="34" font-size="12.5">408 应用题存储结构选型判据</text>
    <text class="fig-accent" x="512" y="72" text-anchor="middle" font-size="12">优先选顺序表 SqList</text>
    <text class="fig-muted" x="512" y="92" text-anchor="middle" font-size="11">① 表长稳定可预估　② 按位序随机访问频繁</text>
    <text class="fig-muted" x="512" y="109" text-anchor="middle" font-size="11">③ 插入删除极少（或仅在表尾增删）</text>
    <text class="fig-orange" x="512" y="156" text-anchor="middle" font-size="12">优先选链表 LinkList</text>
    <text class="fig-muted" x="512" y="176" text-anchor="middle" font-size="11">① 表长动态剧烈变化　② 中间位置频繁增删</text>
    <text class="fig-muted" x="512" y="193" text-anchor="middle" font-size="11">③ 需原地合并或拆分（无需大片连续内存）</text>
  </svg>
  <figcaption>结点存储密度定量对比与顺序表、链表的核心选型判据</figcaption>
</figure>

### 线性表的合并（求并集）

问题：`La`、`Lb` 分别表示两个集合，求 $A\cup B$，重复元素只保留一个，结果仍存于 `La`。

思路：依次取出 `Lb` 的每个元素，在 `La` 中查找；不存在则插入到 `La` 表尾，已存在则丢弃。

```c
void unionList(List &La, List Lb) {
    int La_len = ListLength(La), Lb_len = ListLength(Lb);
    ElemType e;
    for (int i = 1; i <= Lb_len; ++i) {
        GetElem(Lb, i, e);                 // 取 Lb 第 i 个元素
        if (!LocateElem(La, e))            // La 中不存在 e
            ListInsert(&La, ++La_len, e);  // 插到 La 表尾
    }
}
```

时间 $O(|La| \times |Lb|)$：`Lb` 的每个元素都要在 `La` 中顺序扫描一遍。算法只调用基本操作，与顺序/链式存储无关，两种存储都能实现，具体效率需分别分析。

### 有序表的合并

前提：两表元素按值**非递减**排列（允许相等，故不叫“递增”）。合并结果仍非递减，**相同元素全部保留**（区别于求并集）。

**顺序表实现**：三个指针 `pa`、`pb`、`pc`，每次取两表当前较小者放入 `Lc`，某表耗尽后把另一表剩余段整体复制。

```c
pa = La.elem;  pb = Lb.elem;
Lc.length = La.length + Lb.length;
pc = Lc.elem = new ElemType[Lc.length];
pa_last = La.elem + La.length - 1;
pb_last = Lb.elem + Lb.length - 1;

while (pa <= pa_last && pb <= pb_last) {
    if (*pa <= *pb) *pc++ = *pa++;     // 相等时取 a 表，保证稳定
    else            *pc++ = *pb++;
}
while (pa <= pa_last) *pc++ = *pa++;   // 复制 a 表剩余
while (pb <= pb_last) *pc++ = *pb++;   // 复制 b 表剩余
```

时间 $O(m+n)$，空间 $O(m+n)$（必须另开数组）。

**链表实现**：以 `La` 的头结点作为 `Lc` 的头结点，`pc` 指向结果表尾，摘下较小结点直接挂到 `pc` 之后，全程原地操作。

```c
pa = La->next;  pb = Lb->next;
pc = Lc = La;                          // 复用 La 的头结点
while (pa && pb) {
    if (pa->data <= pb->data) { pc->next = pa; pc = pa; pa = pa->next; }
    else                      { pc->next = pb; pc = pb; pb = pb->next; }
}
pc->next = pa ? pa : pb;               // 剩余段整体接上（三目运算符）
delete Lb;                             // 释放 Lb 的头结点
```

时间 $O(m+n)$，空间 $O(1)$。

> **★考点**：两种实现时间同为 $O(m+n)$，差别在空间——顺序表 $O(m+n)$ 且长度需预先算好，链表 $O(1)$ 且可原地合并。链表版因此更适合长表、变长场景。

<figure class="cpd-figure not-content" id="wz-w1-fig-10">
  <svg viewBox="0 0 680 268" role="img" aria-label="有序表归并对比：顺序表开辟新数组与单链表原地重连指针">
    <defs>
      <marker id="wz-w1-arr-10m" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="18" y="14" width="318" height="238" rx="6"/>
    <rect class="fig-box-subtle" x="348" y="14" width="314" height="238" rx="6"/>
    <line class="fig-line-dashed" x1="94" y1="88" x2="72" y2="152" marker-end="url(#wz-w1-arr-10m)"/>
    <line class="fig-line-dashed" x1="202" y1="88" x2="112" y2="152" marker-end="url(#wz-w1-arr-10m)"/>
    <line class="fig-line-dashed" x1="138" y1="88" x2="152" y2="152" marker-end="url(#wz-w1-arr-10m)"/>
    <rect class="fig-box-blue" x="72" y="56" width="44" height="30" rx="3"/>
    <rect class="fig-box-blue" x="116" y="56" width="44" height="30" rx="3"/>
    <rect class="fig-box-orange" x="180" y="56" width="44" height="30" rx="3"/>
    <rect class="fig-box-orange" x="224" y="56" width="44" height="30" rx="3"/>
    <rect class="fig-box-orange" x="268" y="56" width="44" height="30" rx="3"/>
    <rect class="fig-box" x="50" y="156" width="40" height="30" rx="3"/>
    <rect class="fig-box" x="90" y="156" width="40" height="30" rx="3"/>
    <rect class="fig-box" x="130" y="156" width="40" height="30" rx="3"/>
    <rect class="fig-box" x="170" y="156" width="40" height="30" rx="3"/>
    <rect class="fig-box" x="210" y="156" width="40" height="30" rx="3"/>
    <text class="fig-title" x="32" y="34" font-size="12.5">顺序表合并：需新开数组 Lc[m + n]</text>
    <text class="fig-blue" x="94" y="50" text-anchor="middle" font-size="10.5">La (pa)</text>
    <text class="fig-blue" x="94" y="75" text-anchor="middle" font-size="12">1</text>
    <text class="fig-blue" x="138" y="75" text-anchor="middle" font-size="12">7</text>
    <text class="fig-orange" x="202" y="50" text-anchor="middle" font-size="10.5">Lb (pb)</text>
    <text class="fig-orange" x="202" y="75" text-anchor="middle" font-size="12">2</text>
    <text class="fig-orange" x="246" y="75" text-anchor="middle" font-size="12">7</text>
    <text class="fig-orange" x="290" y="75" text-anchor="middle" font-size="12">9</text>
    <text class="fig-label" x="70" y="175" text-anchor="middle" font-size="12">1</text>
    <text class="fig-label" x="110" y="175" text-anchor="middle" font-size="12">2</text>
    <text class="fig-label" x="150" y="175" text-anchor="middle" font-size="12">7</text>
    <text class="fig-label" x="190" y="175" text-anchor="middle" font-size="12">7</text>
    <text class="fig-label" x="230" y="175" text-anchor="middle" font-size="12">9</text>
    <text class="fig-muted" x="177" y="210" text-anchor="middle" font-size="11">相等元素全保留（区别于集合求并集）</text>
    <text class="fig-orange" x="177" y="232" text-anchor="middle" font-size="11.5">T(n) = O(m + n)，S(n) = O(m + n)</text>
    <line class="fig-line-accent" x1="422" y1="72" x2="454" y2="72" marker-end="url(#wz-w1-arr-10m)"/>
    <path class="fig-line-accent" d="M 502 88 L 468 128" marker-end="url(#wz-w1-arr-10m)"/>
    <path class="fig-line-accent" d="M 502 144 L 548 88" marker-end="url(#wz-w1-arr-10m)"/>
    <path class="fig-line-accent" d="M 578 88 L 558 128" marker-end="url(#wz-w1-arr-10m)"/>
    <line class="fig-line-accent" x1="592" y1="144" x2="610" y2="144" marker-end="url(#wz-w1-arr-10m)"/>
    <rect class="fig-box-purple" x="364" y="56" width="58" height="32" rx="4"/>
    <rect class="fig-box-blue" x="456" y="56" width="48" height="32" rx="4"/>
    <rect class="fig-box-blue" x="550" y="56" width="48" height="32" rx="4"/>
    <rect class="fig-box-red" x="364" y="128" width="58" height="32" rx="4"/>
    <rect class="fig-box-orange" x="456" y="128" width="48" height="32" rx="4"/>
    <rect class="fig-box-orange" x="544" y="128" width="48" height="32" rx="4"/>
    <rect class="fig-box-orange" x="612" y="128" width="38" height="32" rx="4"/>
    <text class="fig-title" x="362" y="34" font-size="12.5">单链表合并：复用 La 头结点原地穿线</text>
    <text class="fig-purple" x="393" y="76" text-anchor="middle" font-size="11">Lc=La</text>
    <text class="fig-blue" x="480" y="76" text-anchor="middle" font-size="12">1</text>
    <text class="fig-blue" x="574" y="76" text-anchor="middle" font-size="12">7</text>
    <text class="fig-red" x="393" y="148" text-anchor="middle" font-size="10.5">删Lb头</text>
    <text class="fig-orange" x="480" y="148" text-anchor="middle" font-size="12">2</text>
    <text class="fig-orange" x="568" y="148" text-anchor="middle" font-size="12">7</text>
    <text class="fig-orange" x="631" y="148" text-anchor="middle" font-size="12">9</text>
    <text class="fig-muted" x="505" y="190" text-anchor="middle" font-size="11">尾指针 pc 摘小者串接，剩余链直接 pc-&gt;next 挂上</text>
    <text class="fig-muted" x="505" y="210" text-anchor="middle" font-size="11">不新建任何元素结点，仅释放 Lb 头结点</text>
    <text class="fig-green" x="505" y="232" text-anchor="middle" font-size="11.5">T(n) = O(m + n)，S(n) = O(1) 原地归并</text>
  </svg>
  <figcaption>非递减有序表归并：顺序表需 O(m + n) 辅助数组，单链表复用原结点实现 O(1) 辅助空间</figcaption>
</figure>

> **交互演示**：[有序表合并](/lab/chapter-2/#lab-listMerge)

### 案例：多项式运算与图书信息管理

**稠密一元多项式** $P_n(x)=p_0+p_1x+\cdots+p_nx^n$：把系数序列看成线性表，指数隐含在下标中（$p_i$ 是 $x^i$ 的系数）。顺序表最自然：两多项式相加即**同下标元素相加**，某表先结束则剩余项直接照抄。求减、求积同理。缺点：系数为 0 的项也占空间。

**稀疏多项式**：只存非零项，每项保存“系数 + 指数”一对。

```c
typedef struct PNode {
    float coef;             // 系数
    int   exp;              // 指数
    struct PNode *next;
} PNode, *Polynomial;
```

建立：先建头结点，再逐项生成结点，用尾插法（保持输入顺序）或头插法（顺序相反）。求和（`pa`、`pb` 均按指数递增）：

- 指数相等：系数相加。和不为 0 → 结果存入 `pa` 结点，释放 `pb` 结点；和为 0（互为相反数）→ **两个结点都删除**；
- `pa` 指数小：摘下 `pa` 结点接入结果链，`pa` 后移；
- `pb` 指数小：摘下 `pb` 结点接入结果链，`pb` 后移；
- 某链为空：另一链剩余段整体接到结果链尾；复用 `La` 头结点，释放 `Lb` 头结点。

链式存储在这里解决了顺序表版的两个痛点：结果项数不定（最少 0、最多 $m+n$）导致数组大小难定；必须另开数组导致空间效率低。

<figure class="cpd-figure not-content" id="wz-w1-fig-11">
  <svg viewBox="0 0 680 286" role="img" aria-label="稀疏多项式单链表相加的三种指数比较处理与合并结果">
    <defs>
      <marker id="wz-w1-arr-11p" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="18" y="14" width="644" height="258" rx="6"/>
    <line class="fig-line" x1="88" y1="68" x2="112" y2="68" marker-end="url(#wz-w1-arr-11p)"/>
    <line class="fig-line" x1="196" y1="68" x2="220" y2="68" marker-end="url(#wz-w1-arr-11p)"/>
    <line class="fig-line" x1="304" y1="68" x2="328" y2="68" marker-end="url(#wz-w1-arr-11p)"/>
    <line class="fig-line" x1="412" y1="68" x2="436" y2="68" marker-end="url(#wz-w1-arr-11p)"/>
    <line class="fig-line" x1="88" y1="126" x2="220" y2="126" marker-end="url(#wz-w1-arr-11p)"/>
    <line class="fig-line" x1="304" y1="126" x2="328" y2="126" marker-end="url(#wz-w1-arr-11p)"/>
    <line class="fig-line" x1="412" y1="126" x2="436" y2="126" marker-end="url(#wz-w1-arr-11p)"/>
    <line class="fig-line-accent" x1="88" y1="214" x2="112" y2="214" marker-end="url(#wz-w1-arr-11p)"/>
    <line class="fig-line-accent" x1="196" y1="214" x2="220" y2="214" marker-end="url(#wz-w1-arr-11p)"/>
    <line class="fig-line-accent" x1="304" y1="214" x2="328" y2="214" marker-end="url(#wz-w1-arr-11p)"/>
    <line class="fig-line-accent" x1="412" y1="214" x2="436" y2="214" marker-end="url(#wz-w1-arr-11p)"/>
    <rect class="fig-box-purple" x="34" y="52" width="54" height="32" rx="4"/>
    <rect class="fig-box-blue" x="114" y="52" width="82" height="32" rx="4"/>
    <rect class="fig-box-green" x="222" y="52" width="82" height="32" rx="4"/>
    <rect class="fig-box-red" x="330" y="52" width="82" height="32" rx="4"/>
    <rect class="fig-box-blue" x="438" y="52" width="86" height="32" rx="4"/>
    <rect class="fig-box-purple" x="34" y="110" width="54" height="32" rx="4"/>
    <rect class="fig-box-green" x="222" y="110" width="82" height="32" rx="4"/>
    <rect class="fig-box-orange" x="330" y="110" width="82" height="32" rx="4"/>
    <rect class="fig-box-red" x="438" y="110" width="86" height="32" rx="4"/>
    <rect class="fig-box-purple" x="34" y="198" width="54" height="32" rx="4"/>
    <rect class="fig-box" x="114" y="198" width="82" height="32" rx="4"/>
    <rect class="fig-box-green" x="222" y="198" width="82" height="32" rx="4"/>
    <rect class="fig-box" x="330" y="198" width="82" height="32" rx="4"/>
    <rect class="fig-box" x="438" y="198" width="86" height="32" rx="4"/>
    <rect class="fig-box" x="538" y="52" width="110" height="178" rx="5"/>
    <text class="fig-title" x="34" y="34" font-size="12.5">稀疏多项式相加：P_A = 7 + 3x + 9x⁸ + 5x¹⁷　与　P_B = 8x + 22x⁷ − 9x⁸</text>
    <text class="fig-purple" x="61" y="72" text-anchor="middle" font-size="11.5">La</text>
    <text class="fig-blue" x="155" y="72" text-anchor="middle" font-size="11.5">(7, 0)</text>
    <text class="fig-green" x="263" y="72" text-anchor="middle" font-size="11.5">(3, 1)</text>
    <text class="fig-red" x="371" y="72" text-anchor="middle" font-size="11.5">(9, 8)</text>
    <text class="fig-blue" x="481" y="72" text-anchor="middle" font-size="11.5">(5, 17) ∧</text>
    <text class="fig-purple" x="61" y="130" text-anchor="middle" font-size="11.5">Lb</text>
    <text class="fig-green" x="263" y="130" text-anchor="middle" font-size="11.5">(8, 1)</text>
    <text class="fig-orange" x="371" y="130" text-anchor="middle" font-size="11.5">(22, 7)</text>
    <text class="fig-red" x="481" y="130" text-anchor="middle" font-size="11.5">(−9, 8) ∧</text>
    <text class="fig-muted" x="280" y="172" text-anchor="middle" font-size="11">↓ 按指数升序同步扫描 pa、pb，原地重连指针生成和多项式 ↓</text>
    <text class="fig-purple" x="61" y="218" text-anchor="middle" font-size="11.5">结果</text>
    <text class="fig-label" x="155" y="218" text-anchor="middle" font-size="11.5">(7, 0)</text>
    <text class="fig-green" x="263" y="218" text-anchor="middle" font-size="11.5">(11, 1)</text>
    <text class="fig-label" x="371" y="218" text-anchor="middle" font-size="11.5">(22, 7)</text>
    <text class="fig-label" x="481" y="218" text-anchor="middle" font-size="11.5">(5, 17) ∧</text>
    <text class="fig-muted" x="280" y="254" text-anchor="middle" font-size="11">最终结果：7 + 11x + 22x⁷ + 5x¹⁷（x⁸ 项正负抵消被双删，不留零系数结点）</text>
    <text class="fig-blue" x="593" y="76" text-anchor="middle" font-size="11">① 指数小</text>
    <text class="fig-muted" x="593" y="94" text-anchor="middle" font-size="10">直接摘入结果链</text>
    <text class="fig-green" x="593" y="126" text-anchor="middle" font-size="11">② 指数等≠0</text>
    <text class="fig-muted" x="593" y="144" text-anchor="middle" font-size="10">改 pa 系数，删 pb</text>
    <text class="fig-red" x="593" y="176" text-anchor="middle" font-size="11">③ 指数等=0</text>
    <text class="fig-muted" x="593" y="194" text-anchor="middle" font-size="10">pa、pb 同时释放</text>
    <text class="fig-muted" x="593" y="216" text-anchor="middle" font-size="10">辅助空间 O(1)</text>
  </svg>
  <figcaption>稀疏多项式单链表求和三分支处理：指数不等摘小者，指数相等按系数和留一或双删</figcaption>
</figure>

**图书信息管理**：数据元素是复合类型，含书号、书名、定价三个数据项。

```c
typedef struct {
    char ISBN[20];
    char name[40];
    int  price;
} Book;
```

顺序表：`Book elem[MAXSIZE]; int length;`；链表：结点 `data` 为 `Book`、另有 `next` 域。查询（按书名）、插入、删除、修改都直接复用本章基本操作。

存储结构选择沿用同一判据：图书数量稳定、少增删、常按序号查询 → 顺序表；数量变化大、频繁增删 → 链表。

<figure class="cpd-figure not-content" id="wz-w1-fig-12">
  <svg viewBox="0 0 680 236" role="img" aria-label="图书信息管理案例中复合结构类型 Book 在顺序表与单链表中的存储对比">
    <defs>
      <marker id="wz-w1-arr-12b" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="18" y="14" width="644" height="96" rx="6"/>
    <rect class="fig-box" x="34" y="46" width="232" height="44" rx="4"/>
    <line class="fig-divider" x1="108" y1="46" x2="108" y2="90"/>
    <line class="fig-divider" x1="204" y1="46" x2="204" y2="90"/>
    <rect class="fig-box" x="266" y="46" width="232" height="44" rx="4"/>
    <line class="fig-divider" x1="340" y1="46" x2="340" y2="90"/>
    <line class="fig-divider" x1="436" y1="46" x2="436" y2="90"/>
    <rect class="fig-box-dashed" x="498" y="46" width="66" height="44"/>
    <rect class="fig-box-blue" x="576" y="46" width="70" height="44" rx="4"/>
    <text class="fig-title" x="34" y="34" font-size="12.5">图书表顺序实现：Book elem[MAXSIZE]（适合馆藏稳定、按序号随机检索）</text>
    <text class="fig-label" x="71" y="66" text-anchor="middle" font-size="11">978-7-115</text>
    <text class="fig-muted" x="71" y="82" text-anchor="middle" font-size="10">ISBN</text>
    <text class="fig-label" x="156" y="66" text-anchor="middle" font-size="11">数据结构</text>
    <text class="fig-muted" x="156" y="82" text-anchor="middle" font-size="10">name</text>
    <text class="fig-accent" x="235" y="66" text-anchor="middle" font-size="11">59</text>
    <text class="fig-muted" x="235" y="82" text-anchor="middle" font-size="10">price</text>
    <text class="fig-label" x="303" y="66" text-anchor="middle" font-size="11">978-7-302</text>
    <text class="fig-muted" x="303" y="82" text-anchor="middle" font-size="10">ISBN</text>
    <text class="fig-label" x="388" y="66" text-anchor="middle" font-size="11">操作系统</text>
    <text class="fig-muted" x="388" y="82" text-anchor="middle" font-size="10">name</text>
    <text class="fig-accent" x="467" y="66" text-anchor="middle" font-size="11">68</text>
    <text class="fig-muted" x="467" y="82" text-anchor="middle" font-size="10">price</text>
    <text class="fig-muted" x="531" y="72" text-anchor="middle" font-size="11">…</text>
    <text class="fig-blue" x="611" y="66" text-anchor="middle" font-size="12">length</text>
    <text class="fig-muted" x="611" y="82" text-anchor="middle" font-size="10">当前册数</text>
    <rect class="fig-box-subtle" x="18" y="120" width="644" height="102" rx="6"/>
    <line class="fig-line-accent" x1="50" y1="176" x2="72" y2="176" marker-end="url(#wz-w1-arr-12b)"/>
    <line class="fig-line-accent" x1="138" y1="176" x2="164" y2="176" marker-end="url(#wz-w1-arr-12b)"/>
    <line class="fig-line-accent" x1="392" y1="176" x2="418" y2="176" marker-end="url(#wz-w1-arr-12b)"/>
    <rect class="fig-box-purple" x="74" y="154" width="64" height="44" rx="4"/>
    <rect class="fig-box" x="166" y="154" width="226" height="44" rx="4"/>
    <line class="fig-divider" x1="234" y1="154" x2="234" y2="198"/>
    <line class="fig-divider" x1="312" y1="154" x2="312" y2="198"/>
    <line class="fig-divider" x1="354" y1="154" x2="354" y2="198"/>
    <rect class="fig-box" x="420" y="154" width="226" height="44" rx="4"/>
    <line class="fig-divider" x1="488" y1="154" x2="488" y2="198"/>
    <line class="fig-divider" x1="566" y1="154" x2="566" y2="198"/>
    <line class="fig-divider" x1="608" y1="154" x2="608" y2="198"/>
    <text class="fig-title" x="34" y="140" font-size="12.5">图书表链式实现：LNode.data = Book（适合频繁新书入库与旧书下架）</text>
    <text class="fig-accent" x="38" y="180" text-anchor="middle" font-size="12">L</text>
    <text class="fig-purple" x="106" y="180" text-anchor="middle" font-size="11">头结点</text>
    <text class="fig-label" x="200" y="180" text-anchor="middle" font-size="10.5">978-7-115</text>
    <text class="fig-label" x="273" y="180" text-anchor="middle" font-size="11">数据结构</text>
    <text class="fig-accent" x="333" y="180" text-anchor="middle" font-size="11">59</text>
    <circle class="fig-dot" cx="373" cy="176" r="2.8"/>
    <text class="fig-label" x="454" y="180" text-anchor="middle" font-size="10.5">978-7-302</text>
    <text class="fig-label" x="527" y="180" text-anchor="middle" font-size="11">操作系统</text>
    <text class="fig-accent" x="587" y="180" text-anchor="middle" font-size="11">68</text>
    <text class="fig-muted" x="627" y="180" text-anchor="middle" font-size="12">∧</text>
  </svg>
  <figcaption>复合元素（多数据项封装为 struct Book）在顺序表与单链表中的统一建模与复用</figcaption>
</figure>

## 第3章 栈和队列

### 栈与队列：操作受限的线性表

栈和队列**都是线性表**：逻辑结构仍是元素间一对一的线性关系，存储结构同样可以顺序存储或链式存储。它们与一般线性表的唯一区别是**运算规则**——插入和删除的位置被限定在表的端点，因此称为**操作受限的线性表**（线性表的子集）。

| 结构 | 插入位置 | 删除位置 | 访问特点 |
| --- | --- | --- | --- |
| 一般线性表 | 任意 $1 \le i \le n+1$ | 任意 $1 \le i \le n$ | 可随机存取任意元素 |
| 栈 | 仅表尾（栈顶）$n+1$ | 仅表尾（栈顶）$n$ | 后进先出，取中间元素须先弹出其上元素 |
| 队列 | 仅表尾（队尾）$n+1$ | 仅表头（队头）$1$ | 先进先出，只能按入队顺序访问 |

一般线性表在中间插入/删除需要移动元素，在表尾操作则不必移动；栈把操作全部压到表尾，队列则从两端分别操作，这正是它们高效的原因。

<figure class="cpd-figure not-content" id="wz-w2-fig-1">
  <svg viewBox="0 0 700 244" role="img" aria-label="一般线性表、栈与队列的端口操作对比示意图">
    <defs>
      <marker id="wz-w2-arr-1" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="18" y="16" width="210" height="212" rx="8"/>
    <rect class="fig-box-subtle" x="245" y="16" width="210" height="212" rx="8"/>
    <rect class="fig-box-subtle" x="472" y="16" width="210" height="212" rx="8"/>
    <line class="fig-line" stroke="var(--sl-color-orange)" stroke-width="1.5" x1="103" y1="62" x2="103" y2="92" marker-end="url(#wz-w2-arr-1)"/>
    <line class="fig-line" stroke="var(--sl-color-red)" stroke-width="1.5" x1="103" y1="132" x2="103" y2="162" marker-end="url(#wz-w2-arr-1)"/>
    <path class="fig-line-dashed" d="M 112 88 L 194 88" marker-end="url(#wz-w2-arr-1)"/>
    <path class="fig-line" stroke="var(--sl-color-blue)" stroke-width="1.6" d="M 304 58 Q 332 58 336 84" marker-end="url(#wz-w2-arr-1)"/>
    <path class="fig-line" stroke="var(--sl-color-green)" stroke-width="1.6" d="M 364 84 Q 368 58 396 58" marker-end="url(#wz-w2-arr-1)"/>
    <line class="fig-line" stroke="var(--sl-color-gray-4)" stroke-width="2.2" x1="304" y1="86" x2="304" y2="188"/>
    <line class="fig-line" stroke="var(--sl-color-gray-4)" stroke-width="2.2" x1="396" y1="86" x2="396" y2="188"/>
    <line class="fig-line" stroke="var(--sl-color-gray-4)" stroke-width="2.6" x1="302" y1="188" x2="398" y2="188"/>
    <line class="fig-line" stroke="var(--sl-color-gray-4)" stroke-width="2" x1="516" y1="94" x2="640" y2="94"/>
    <line class="fig-line" stroke="var(--sl-color-gray-4)" stroke-width="2" x1="516" y1="134" x2="640" y2="134"/>
    <line class="fig-line" stroke="var(--sl-color-green)" stroke-width="1.6" x1="520" y1="114" x2="484" y2="114" marker-end="url(#wz-w2-arr-1)"/>
    <line class="fig-line" stroke="var(--sl-color-blue)" stroke-width="1.6" x1="670" y1="114" x2="640" y2="114" marker-end="url(#wz-w2-arr-1)"/>
    <rect class="fig-box" x="43" y="96" width="40" height="34" rx="4"/>
    <rect class="fig-box-orange" x="83" y="96" width="40" height="34" rx="4"/>
    <rect class="fig-box" x="123" y="96" width="40" height="34" rx="4"/>
    <rect class="fig-box" x="163" y="96" width="40" height="34" rx="4"/>
    <rect class="fig-box-accent" x="310" y="90" width="80" height="30" rx="4"/>
    <rect class="fig-box-blue" x="310" y="122" width="80" height="30" rx="4"/>
    <rect class="fig-box-blue" x="310" y="154" width="80" height="30" rx="4"/>
    <rect class="fig-box-green" x="522" y="98" width="38" height="32" rx="4"/>
    <rect class="fig-box-blue" x="560" y="98" width="38" height="32" rx="4"/>
    <rect class="fig-box-accent" x="598" y="98" width="38" height="32" rx="4"/>
    <text class="fig-title" x="123" y="38" text-anchor="middle" font-size="12.5">一般线性表（任意位插删）</text>
    <text class="fig-orange" x="103" y="56" text-anchor="middle" font-size="11">任意位插入</text>
    <text class="fig-muted" x="156" y="82" text-anchor="middle" font-size="10.5">需成批搬移</text>
    <text class="fig-label" x="63" y="118" text-anchor="middle" font-size="12">a₁</text>
    <text class="fig-orange" x="103" y="118" text-anchor="middle" font-size="12">aᵢ</text>
    <text class="fig-label" x="143" y="118" text-anchor="middle" font-size="12">…</text>
    <text class="fig-label" x="183" y="118" text-anchor="middle" font-size="12">aₙ</text>
    <text class="fig-red" x="103" y="177" text-anchor="middle" font-size="11">任意位删除</text>
    <text class="fig-muted" x="123" y="202" text-anchor="middle" font-size="11">随机存取 O(1)</text>
    <text class="fig-muted" x="123" y="218" text-anchor="middle" font-size="11">中间插删 O(n)</text>
    <text class="fig-title" x="350" y="38" text-anchor="middle" font-size="12.5">栈 Stack（单端 · LIFO）</text>
    <text class="fig-blue" x="282" y="62" text-anchor="middle" font-size="11">Push</text>
    <text class="fig-green" x="418" y="62" text-anchor="middle" font-size="11">Pop</text>
    <text class="fig-accent" x="350" y="110" text-anchor="middle" font-size="11.5">a₃（top）</text>
    <text class="fig-blue" x="350" y="142" text-anchor="middle" font-size="11.5">a₂</text>
    <text class="fig-blue" x="350" y="174" text-anchor="middle" font-size="11.5">a₁（base）</text>
    <text class="fig-label" x="350" y="204" text-anchor="middle" font-size="11">仅栈顶进出 · 后进先出</text>
    <text class="fig-muted" x="350" y="220" text-anchor="middle" font-size="11">Push / Pop 均 O(1)</text>
    <text class="fig-title" x="577" y="38" text-anchor="middle" font-size="12.5">队列 Queue（双端 · FIFO）</text>
    <text class="fig-green" x="504" y="84" text-anchor="middle" font-size="11">出队端</text>
    <text class="fig-blue" x="652" y="84" text-anchor="middle" font-size="11">入队端</text>
    <text class="fig-green" x="541" y="119" text-anchor="middle" font-size="11.5">a₁</text>
    <text class="fig-blue" x="579" y="119" text-anchor="middle" font-size="11.5">a₂</text>
    <text class="fig-accent" x="617" y="119" text-anchor="middle" font-size="11.5">a₃</text>
    <text class="fig-green" x="536" y="152" text-anchor="middle" font-size="11">front 头删</text>
    <text class="fig-accent" x="620" y="152" text-anchor="middle" font-size="11">rear 尾插</text>
    <text class="fig-label" x="577" y="204" text-anchor="middle" font-size="11">头删尾插 · 先进先出</text>
    <text class="fig-muted" x="577" y="220" text-anchor="middle" font-size="11">EnQueue / DeQueue 均 O(1)</text>
  </svg>
  <figcaption>三类一对一线性结构对比：栈将插删收束到栈顶单端（LIFO），队列分置到队头与队尾两端（FIFO）</figcaption>
</figure>

### 栈的定义与后进先出

**栈（stack）**：仅限定在**表尾**进行插入和删除的线性表。表尾端称**栈顶（top）**，表头端称**栈底（base）**。用 $S=(a_1,a_2,\dots,a_n)$ 表示，$a_1$ 为栈底元素，$a_n$ 为栈顶元素。

- **入栈**（push，也叫进栈、压栈）：在栈顶插入一个元素。
- **出栈**（pop，也叫弹栈）：删除栈顶元素。

栈的操作只在栈顶一端进行，所以最后入栈的元素最先出栈，特性为**后进先出**（LIFO，Last In First Out）。生活例子：往手电筒里装电池只能从一端装入、从同一端取出；洗完的盘子叠放，最后放上去的最先被拿走。

凡是求解过程具有后进先出特性的问题都可以用栈：数制转换、括号匹配、行编辑程序、迷宫求解、表达式求值、八皇后、函数调用与递归调用。

栈与一般线性表的比较：

- 逻辑结构相同，都是一对一关系；
- 存储结构相同，都有顺序栈与链栈；
- 运算规则不同——不能随机存取，要取某个元素必须先把压在它上面的元素逐个出栈。

> **★考点**：给定入栈顺序 $a,b,c$，合法出栈序列共有 **5** 种：$abc$、$acb$、$bac$、$bca$、$cba$；**$cab$ 不可能出现**。因为要让 $c$ 先出栈，$a,b$ 必已全部入栈且 $b$ 压在 $a$ 之上，$c$ 出栈后栈顶只能是 $b$，所以 $b$ 一定先于 $a$ 出栈。入栈与出栈可以交替进行，故同一入栈顺序对应多种出栈顺序。

<figure class="cpd-figure not-content" id="wz-w2-fig-2">
  <svg viewBox="0 0 700 264" role="img" aria-label="入栈序列 a,b,c 的非法出栈序列 cab 证明与卡特兰数 5 种合法出栈序列">
    <defs>
      <marker id="wz-w2-arr-2" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="18" y="16" width="328" height="232" rx="8"/>
    <rect class="fig-box-subtle" x="358" y="16" width="324" height="232" rx="8"/>
    <line class="fig-line" stroke="var(--sl-color-gray-4)" stroke-width="2" x1="48" y1="74" x2="48" y2="188"/>
    <line class="fig-line" stroke="var(--sl-color-gray-4)" stroke-width="2" x1="124" y1="74" x2="124" y2="188"/>
    <line class="fig-line" stroke="var(--sl-color-gray-4)" stroke-width="2.4" x1="46" y1="188" x2="126" y2="188"/>
    <path class="fig-line" stroke="var(--sl-color-green)" stroke-width="1.6" d="M 86 78 Q 92 54 134 54" marker-end="url(#wz-w2-arr-2)"/>
    <line class="fig-line-dashed" x1="132" y1="134" x2="182" y2="134" marker-end="url(#wz-w2-arr-2)"/>
    <line class="fig-line" stroke="var(--sl-color-gray-4)" stroke-width="2" x1="190" y1="74" x2="190" y2="188"/>
    <line class="fig-line" stroke="var(--sl-color-gray-4)" stroke-width="2" x1="266" y1="74" x2="266" y2="188"/>
    <line class="fig-line" stroke="var(--sl-color-gray-4)" stroke-width="2.4" x1="188" y1="188" x2="268" y2="188"/>
    <line class="fig-line" stroke="var(--sl-color-orange)" stroke-width="1.5" x1="308" y1="134" x2="270" y2="134" marker-end="url(#wz-w2-arr-2)"/>
    <rect class="fig-box-green" x="54" y="82" width="64" height="32" rx="4"/>
    <rect class="fig-box-blue" x="54" y="118" width="64" height="32" rx="4"/>
    <rect class="fig-box-blue" x="54" y="154" width="64" height="32" rx="4"/>
    <rect class="fig-box-dashed" x="196" y="82" width="64" height="32" rx="4"/>
    <rect class="fig-box-orange" x="196" y="118" width="64" height="32" rx="4"/>
    <rect class="fig-box-red" x="196" y="154" width="64" height="32" rx="4"/>
    <rect class="fig-box-red" x="30" y="200" width="304" height="36" rx="5"/>
    <rect class="fig-box" x="372" y="48" width="296" height="24" rx="4"/>
    <rect class="fig-box" x="372" y="76" width="296" height="24" rx="4"/>
    <rect class="fig-box" x="372" y="104" width="296" height="24" rx="4"/>
    <rect class="fig-box" x="372" y="132" width="296" height="24" rx="4"/>
    <rect class="fig-box" x="372" y="160" width="296" height="24" rx="4"/>
    <rect class="fig-box-accent" x="372" y="192" width="296" height="44" rx="5"/>
    <text class="fig-title" x="182" y="36" text-anchor="middle" font-size="12.5">反证：入栈 a, b, c 为何不可能出栈 c, a, b？</text>
    <text class="fig-green" x="140" y="58" font-size="11">① c 首出</text>
    <text class="fig-green" x="86" y="103" text-anchor="middle" font-size="12">c</text>
    <text class="fig-blue" x="86" y="139" text-anchor="middle" font-size="12">b</text>
    <text class="fig-blue" x="86" y="175" text-anchor="middle" font-size="12">a</text>
    <text class="fig-muted" x="228" y="103" text-anchor="middle" font-size="11">已弹出</text>
    <text class="fig-orange" x="228" y="139" text-anchor="middle" font-size="12">b（栈顶）</text>
    <text class="fig-red" x="228" y="175" text-anchor="middle" font-size="12">a（被压）</text>
    <text class="fig-orange" x="312" y="138" font-size="11.5">top</text>
    <text class="fig-red" x="182" y="215" text-anchor="middle" font-size="11.5">② c 出栈时 a, b 必已在栈中，且 b 封住栈顶</text>
    <text class="fig-red" x="182" y="230" text-anchor="middle" font-size="11">a 绝不可能越过 b 先出栈 → cab（3,1,2）非法！</text>
    <text class="fig-title" x="520" y="36" text-anchor="middle" font-size="12.5">n = 3 全部 5 种合法出栈序列（卡特兰数）</text>
    <text class="fig-green" x="384" y="64" font-size="11.5">① abc</text>
    <text class="fig-muted" x="436" y="64" font-size="11">入a出a → 入b出b → 入c出c</text>
    <text class="fig-green" x="384" y="92" font-size="11.5">② acb</text>
    <text class="fig-muted" x="436" y="92" font-size="11">入a出a → 入b入c → 出c出b</text>
    <text class="fig-green" x="384" y="120" font-size="11.5">③ bac</text>
    <text class="fig-muted" x="436" y="120" font-size="11">入a入b → 出b出a → 入c出c</text>
    <text class="fig-green" x="384" y="148" font-size="11.5">④ bca</text>
    <text class="fig-muted" x="436" y="148" font-size="11">入a入b出b → 入c出c → 出a</text>
    <text class="fig-green" x="384" y="176" font-size="11.5">⑤ cba</text>
    <text class="fig-muted" x="436" y="176" font-size="11">入a入b入c → 出c出b出a（全逆序）</text>
    <text class="fig-accent" x="520" y="210" text-anchor="middle" font-size="11.5">合法种数 Cₙ = C(2n, n) / (n + 1)（n=3 为 5，n=4 为 14）</text>
    <text class="fig-label" x="520" y="228" text-anchor="middle" font-size="11">秒杀判据：任一元素出栈后，比它早入栈且未出的必逆序</text>
  </svg>
  <figcaption>LIFO 出栈序列合法性判定：c 先出则栈内残留 a, b 必以 b → a 逆序弹出，故 cab 非法</figcaption>
</figure>

### 栈的抽象数据类型

```
ADT Stack {
  数据对象：D = { a_i | a_i ∈ ElemSet, i = 1,2,…,n, n ≥ 0 }
  数据关系：R = { <a_{i-1}, a_i> | a_{i-1}, a_i ∈ D, i = 2,…,n }
            // 与线性表相同的前驱后继关系；a_1 为栈底，a_n 为栈顶
  基本操作：
    InitStack(&S)        初始化，构造一个空栈
    DestroyStack(&S)     销毁：释放栈占用的存储空间，栈不再存在
    StackEmpty(S)        判空：空返回 true，否则 false
    StackLength(S)       返回栈中元素个数
    GetTop(S, &e)        用 e 返回栈顶元素（不修改栈）
    ClearStack(&S)       清空：栈本身保留，但重置为空栈
    Push(&S, e)          入栈：在栈顶插入元素 e
    Pop(&S, &e)          出栈：删除栈顶元素，其值由 e 返回
} ADT Stack
```

$n=0$ 时称为**空栈**。入栈、出栈的参数 `&S` 用引用，因为操作会改变栈的状态；`GetTop` 只读，栈顶指针不变。

> **注意**：**销毁**与**清空**不同。销毁是释放整块存储空间，栈对象不复存在；清空只是把栈顶指针移回栈底，空间仍占用，之后还能继续入栈。

### 顺序栈的存储表示

顺序栈用一组地址连续的存储单元（数组）存放栈中元素，元素从栈底到栈顶依次存放，**栈底固定在下标 0**。为便于操作，附设三个成员：

- `base`：栈底指针，指向下标 0 的单元；
- `top`：栈顶指针，**指向栈顶元素之后的那个单元**（下一个可写入位置）；
- `stacksize`：当前分配的数组容量（最多可存元素个数）。

让 `top` 指向栈顶元素之后，而不是指向栈顶元素本身，是为了让边界判断统一、不必额外分支：

$$
\text{栈空：}\ top == base \qquad \text{栈满：}\ top - base == stacksize \qquad \text{元素个数：}\ top - base
$$

两个指针相减得到的是**相隔的元素个数**（不是字节差），且要求两指针指向同一数组。指针加减 1 表示移动一个元素的位置，移动的字节数由元素类型大小决定。

<figure class="cpd-figure not-content" id="wz-fig-7">
  <svg viewBox="0 0 700 272" role="img" aria-label="顺序栈 base 与 top 双指针的空栈、常规态与栈满上溢三态对比">
    <defs>
      <marker id="wz-arr-7" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="18" y="16" width="206" height="240" rx="8"/>
    <rect class="fig-box-subtle" x="238" y="16" width="224" height="240" rx="8"/>
    <rect class="fig-box-subtle" x="476" y="16" width="206" height="240" rx="8"/>
    <line class="fig-line" stroke="var(--sl-color-accent)" stroke-width="1.5" x1="72" y1="191" x2="108" y2="191" marker-end="url(#wz-arr-7)"/>
    <line class="fig-line" stroke="var(--sl-color-blue)" stroke-width="1.5" x1="72" y1="203" x2="108" y2="203" marker-end="url(#wz-arr-7)"/>
    <line class="fig-line" stroke="var(--sl-color-accent)" stroke-width="1.5" x1="296" y1="197" x2="330" y2="197" marker-end="url(#wz-arr-7)"/>
    <line class="fig-line" stroke="var(--sl-color-blue)" stroke-width="1.5" x1="296" y1="107" x2="330" y2="107" marker-end="url(#wz-arr-7)"/>
    <line class="fig-line" stroke="var(--sl-color-accent)" stroke-width="1.5" x1="528" y1="197" x2="562" y2="197" marker-end="url(#wz-arr-7)"/>
    <line class="fig-line" stroke="var(--sl-color-red)" stroke-width="1.5" x1="528" y1="47" x2="562" y2="47" marker-end="url(#wz-arr-7)"/>
    <rect class="fig-box" x="112" y="62" width="76" height="30"/>
    <rect class="fig-box" x="112" y="92" width="76" height="30"/>
    <rect class="fig-box" x="112" y="122" width="76" height="30"/>
    <rect class="fig-box" x="112" y="152" width="76" height="30"/>
    <rect class="fig-box" x="112" y="182" width="76" height="30"/>
    <rect class="fig-box" x="334" y="62" width="78" height="30"/>
    <rect class="fig-box-accent" x="334" y="92" width="78" height="30"/>
    <rect class="fig-box-blue" x="334" y="122" width="78" height="30"/>
    <rect class="fig-box-blue" x="334" y="152" width="78" height="30"/>
    <rect class="fig-box-blue" x="334" y="182" width="78" height="30"/>
    <rect class="fig-box-dashed" x="566" y="34" width="76" height="28"/>
    <rect class="fig-box-orange" x="566" y="62" width="76" height="30"/>
    <rect class="fig-box-blue" x="566" y="92" width="76" height="30"/>
    <rect class="fig-box-blue" x="566" y="122" width="76" height="30"/>
    <rect class="fig-box-blue" x="566" y="152" width="76" height="30"/>
    <rect class="fig-box-blue" x="566" y="182" width="76" height="30"/>
    <text class="fig-title" x="121" y="38" text-anchor="middle" font-size="12.5">① 空栈（InitStack）</text>
    <text class="fig-accent" x="68" y="193" text-anchor="end" font-size="11">base</text>
    <text class="fig-blue" x="68" y="207" text-anchor="end" font-size="11">top</text>
    <text class="fig-muted" x="150" y="81" text-anchor="middle" font-size="11">空</text>
    <text class="fig-muted" x="150" y="111" text-anchor="middle" font-size="11">空</text>
    <text class="fig-muted" x="150" y="141" text-anchor="middle" font-size="11">空</text>
    <text class="fig-muted" x="150" y="171" text-anchor="middle" font-size="11">空</text>
    <text class="fig-muted" x="150" y="201" text-anchor="middle" font-size="11">空</text>
    <text class="fig-muted" x="196" y="81" font-size="10.5">4</text>
    <text class="fig-muted" x="196" y="111" font-size="10.5">3</text>
    <text class="fig-muted" x="196" y="141" font-size="10.5">2</text>
    <text class="fig-muted" x="196" y="171" font-size="10.5">1</text>
    <text class="fig-muted" x="196" y="201" font-size="10.5">0</text>
    <text class="fig-label" x="121" y="230" text-anchor="middle" font-size="11.5">top == base</text>
    <text class="fig-muted" x="121" y="246" text-anchor="middle" font-size="10.5">再 Pop → 下溢（结束判据）</text>
    <text class="fig-title" x="350" y="38" text-anchor="middle" font-size="12.5">② 非空栈（含 3 个元素）</text>
    <text class="fig-blue" x="292" y="111" text-anchor="end" font-size="11.5">top</text>
    <text class="fig-accent" x="292" y="201" text-anchor="end" font-size="11.5">base</text>
    <text class="fig-muted" x="373" y="81" text-anchor="middle" font-size="11">空</text>
    <text class="fig-accent" x="373" y="111" text-anchor="middle" font-size="11">待写位</text>
    <text class="fig-blue" x="373" y="141" text-anchor="middle" font-size="12">a₃</text>
    <text class="fig-blue" x="373" y="171" text-anchor="middle" font-size="12">a₂</text>
    <text class="fig-blue" x="373" y="201" text-anchor="middle" font-size="12">a₁</text>
    <text class="fig-muted" x="420" y="81" font-size="10.5">4</text>
    <text class="fig-accent" x="420" y="111" font-size="10.5">3</text>
    <text class="fig-muted" x="420" y="141" font-size="10.5">2</text>
    <text class="fig-muted" x="420" y="171" font-size="10.5">1</text>
    <text class="fig-muted" x="420" y="201" font-size="10.5">0</text>
    <text class="fig-blue" x="350" y="230" text-anchor="middle" font-size="11.5">栈长 = top − base = 3</text>
    <text class="fig-muted" x="350" y="246" text-anchor="middle" font-size="10.5">*top++ = e / e = *--top</text>
    <text class="fig-title" x="579" y="29" text-anchor="middle" font-size="12">③ 栈满（stacksize = 5）</text>
    <text class="fig-red" x="524" y="51" text-anchor="end" font-size="11">top</text>
    <text class="fig-accent" x="524" y="201" text-anchor="end" font-size="11">base</text>
    <text class="fig-red" x="604" y="52" text-anchor="middle" font-size="10.5">越界位 5</text>
    <text class="fig-orange" x="604" y="81" text-anchor="middle" font-size="12">a₅</text>
    <text class="fig-blue" x="604" y="111" text-anchor="middle" font-size="12">a₄</text>
    <text class="fig-blue" x="604" y="141" text-anchor="middle" font-size="12">a₃</text>
    <text class="fig-blue" x="604" y="171" text-anchor="middle" font-size="12">a₂</text>
    <text class="fig-blue" x="604" y="201" text-anchor="middle" font-size="12">a₁</text>
    <text class="fig-muted" x="650" y="81" font-size="10.5">4</text>
    <text class="fig-muted" x="650" y="111" font-size="10.5">3</text>
    <text class="fig-muted" x="650" y="141" font-size="10.5">2</text>
    <text class="fig-muted" x="650" y="171" font-size="10.5">1</text>
    <text class="fig-muted" x="650" y="201" font-size="10.5">0</text>
    <text class="fig-red" x="579" y="230" text-anchor="middle" font-size="11">top − base == stacksize</text>
    <text class="fig-red" x="579" y="246" text-anchor="middle" font-size="10.5">再 Push → 上溢（错误）</text>
  </svg>
  <figcaption>教材顺序栈（top 指向栈顶之上空单元）三态对比：空栈、常规态与栈满上溢边界</figcaption>
</figure>

```c
typedef struct {
    SElemType *base;    // 栈底指针，指向下标 0
    SElemType *top;     // 栈顶指针，指向栈顶元素之后
    int stacksize;      // 数组容量，由符号常量 MAXSIZE（如 100）指定
} SqStack;
```

两种溢出：

- **上溢（overflow）**：栈已满（`top - base == stacksize`）仍要入栈，数组下标越界，是**错误**。处理办法：返回错误值，或另分配一块更大的空间并把原栈内容复制过去（费时，元素多时一般不用）。
- **下溢（underflow）**：栈已空（`top == base`）仍要出栈。它通常是“处理结束”的**结束条件**，一般不当作错误特殊处理。

顺序栈的优点是入栈、出栈简单方便，缺点是容量固定、容易溢出。

### 顺序栈的基本操作

**初始化** `InitStack(&S)`：分配 `stacksize` 个元素的数组，`base` 指向首元素，`top = base`，记录容量；分配失败则退出。

```c
Status InitStack(SqStack &S) {
    S.base = new SElemType[MAXSIZE];
    if (!S.base) exit(OVERFLOW);   // 存储分配失败
    S.top = S.base;                // 空栈
    S.stacksize = MAXSIZE;
    return OK;
}
```

**判空** `return S.top == S.base;`　**求长** `return S.top - S.base;`

**清空** `if (S.base) S.top = S.base;`——只移指针，不清除单元内容，`top` 之上的数据视为无效。

**销毁**：`if (S.base) { delete S.base; S.stacksize = 0; S.base = S.top = NULL; }`

**入栈**（算法 3.2）：先判满，再存入 `top` 所指单元，最后 `top` 后移一格。

```c
Status Push(SqStack &S, SElemType e) {
    if (S.top - S.base == S.stacksize) return ERROR;  // 上溢
    *S.top++ = e;      // 等价于 *S.top = e; S.top = S.top + 1;
    return OK;
}
```

**出栈**：先判空，再把 `top` 下移一格，然后取出该单元的值。

```c
Status Pop(SqStack &S, SElemType &e) {
    if (S.top == S.base) return ERROR;   // 空栈，下溢
    e = *--S.top;      // 等价于 --S.top; e = *S.top;
    return OK;
}
```

> **注意**：`*S.top++ = e` 中后缀 `++` 优先级高于 `*`，所以先向 `top` 当前所指单元赋值、再把 `top` 加 1，恰好是入栈的正确顺序；若写成 `*++S.top = e` 则变成先移指针再赋值，语义错误。同理 `e = *--S.top` 是“先下移、再取值”，两步顺序不可交换（出栈时 `top` 已指向栈顶之后的空单元）。

> **★考点**：出栈只移动指针，不删除（也不清零）被弹出单元的数据；数据是否残留与栈的逻辑状态无关。

<figure class="cpd-figure not-content" id="wz-fig-8">
  <svg viewBox="0 0 700 266" role="img" aria-label="top 指向栈顶元素约定及出栈数据残留、两栈共享空间满栈判据对比">
    <defs>
      <marker id="wz-arr-8" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="18" y="16" width="324" height="234" rx="8"/>
    <rect class="fig-box-subtle" x="358" y="16" width="324" height="234" rx="8"/>
    <line class="fig-line" stroke="var(--sl-color-blue)" stroke-width="1.5" x1="68" y1="133" x2="104" y2="133" marker-end="url(#wz-arr-8)"/>
    <line class="fig-line-dashed" x1="86" y1="102" x2="86" y2="127" marker-end="url(#wz-arr-8)"/>
    <line class="fig-line" stroke="var(--sl-color-gray-4)" stroke-width="1.4" x1="68" y1="193" x2="104" y2="193" marker-end="url(#wz-arr-8)"/>
    <line class="fig-line" stroke="var(--sl-color-blue)" stroke-width="1.5" x1="484" y1="74" x2="484" y2="102" marker-end="url(#wz-arr-8)"/>
    <line class="fig-line" stroke="var(--sl-color-purple)" stroke-width="1.5" x1="556" y1="74" x2="556" y2="102" marker-end="url(#wz-arr-8)"/>
    <path class="fig-line" stroke="var(--sl-color-blue)" stroke-width="1.4" d="M 440 154 L 494 154" marker-end="url(#wz-arr-8)"/>
    <path class="fig-line" stroke="var(--sl-color-purple)" stroke-width="1.4" d="M 596 154 L 546 154" marker-end="url(#wz-arr-8)"/>
    <rect class="fig-box" x="108" y="58" width="84" height="30"/>
    <rect class="fig-box-dashed" x="108" y="88" width="84" height="30"/>
    <rect class="fig-box-blue" x="108" y="118" width="84" height="30"/>
    <rect class="fig-box-blue" x="108" y="148" width="84" height="30"/>
    <rect class="fig-box-blue" x="108" y="178" width="84" height="30"/>
    <rect class="fig-box" x="208" y="64" width="120" height="64" rx="5"/>
    <rect class="fig-box-orange" x="208" y="138" width="120" height="68" rx="5"/>
    <rect class="fig-box-blue" x="380" y="106" width="44" height="34"/>
    <rect class="fig-box-blue" x="424" y="106" width="44" height="34"/>
    <rect class="fig-box-accent" x="468" y="106" width="44" height="34"/>
    <rect class="fig-box-purple" x="512" y="106" width="44" height="34"/>
    <rect class="fig-box-purple" x="556" y="106" width="44" height="34"/>
    <rect class="fig-box-purple" x="600" y="106" width="44" height="34"/>
    <rect class="fig-box-red" x="376" y="174" width="288" height="60" rx="5"/>
    <text class="fig-title" x="180" y="38" text-anchor="middle" font-size="12.5">变体约定：top 指向栈顶元素自身</text>
    <text class="fig-blue" x="62" y="137" text-anchor="end" font-size="11.5">top=2</text>
    <text class="fig-muted" x="62" y="197" text-anchor="end" font-size="11">base=0</text>
    <text class="fig-muted" x="150" y="77" text-anchor="middle" font-size="11">空 [4]</text>
    <text class="fig-orange" x="150" y="107" text-anchor="middle" font-size="11">x 残留 [3]</text>
    <text class="fig-blue" x="150" y="137" text-anchor="middle" font-size="11.5">a₃ [2]</text>
    <text class="fig-blue" x="150" y="167" text-anchor="middle" font-size="11.5">a₂ [1]</text>
    <text class="fig-blue" x="150" y="197" text-anchor="middle" font-size="11.5">a₁ [0]</text>
    <text class="fig-blue" x="268" y="84" text-anchor="middle" font-size="11">入栈：data[++top]=e</text>
    <text class="fig-label" x="268" y="102" text-anchor="middle" font-size="11">出栈：e=data[top--]</text>
    <text class="fig-muted" x="268" y="118" text-anchor="middle" font-size="10.5">空栈：top == -1</text>
    <text class="fig-orange" x="268" y="158" text-anchor="middle" font-size="11">★ 出栈仅下移 top</text>
    <text class="fig-orange" x="268" y="176" text-anchor="middle" font-size="10.5">旧值 x 仍留在内存</text>
    <text class="fig-muted" x="268" y="194" text-anchor="middle" font-size="10.5">下次入栈直接覆盖</text>
    <text class="fig-muted" x="180" y="232" text-anchor="middle" font-size="11">满栈：top == stacksize − 1；栈长 = top + 1</text>
    <text class="fig-title" x="520" y="38" text-anchor="middle" font-size="12.5">408 拓展：两栈共享空间（对向生长）</text>
    <text class="fig-blue" x="484" y="68" text-anchor="middle" font-size="11">top0=2</text>
    <text class="fig-purple" x="556" y="68" text-anchor="middle" font-size="11">top1=3</text>
    <text class="fig-blue" x="402" y="127" text-anchor="middle" font-size="11">s₀[0]</text>
    <text class="fig-blue" x="446" y="127" text-anchor="middle" font-size="11">s₀[1]</text>
    <text class="fig-accent" x="490" y="127" text-anchor="middle" font-size="11">s₀[2]</text>
    <text class="fig-purple" x="534" y="127" text-anchor="middle" font-size="11">s₁[3]</text>
    <text class="fig-purple" x="578" y="127" text-anchor="middle" font-size="11">s₁[4]</text>
    <text class="fig-purple" x="622" y="127" text-anchor="middle" font-size="11">s₁[5]</text>
    <text class="fig-blue" x="380" y="158" font-size="10.5">0 号栈底</text>
    <text class="fig-purple" x="652" y="158" text-anchor="end" font-size="10.5">1 号栈底</text>
    <text class="fig-red" x="520" y="194" text-anchor="middle" font-size="11.5">共享栈满判据：top0 + 1 == top1</text>
    <text class="fig-label" x="520" y="211" text-anchor="middle" font-size="10.5">0 号空：top0 == -1；1 号空：top1 == MAXSIZE</text>
    <text class="fig-muted" x="520" y="226" text-anchor="middle" font-size="10.5">一消一长互补利用空间，降低单栈上溢概率</text>
  </svg>
  <figcaption>top 指向栈顶元素的操作次序（含出栈残留说明）与两栈共享一维数组的对向生长模型</figcaption>
</figure>

**过程拆解**（顺序栈，`top` 指向栈顶元素，容量 5）：

| 操作 | 动作 | 结果 |
|:---:|:---|:---|
| 初始 | `top=2`，栈内 `a1,a2` | 栈顶 `a2` |
| 入栈 `x` | `++top` 得 3，`data[3]=x` | 栈内 `a1,a2,x`，`top=3` |
| 出栈 | 先取 `e=data[3]`，再 `--top` 得 2 | 返回 `x`，栈内 `a1,a2` |

> **注意**：入栈是“先移指针再写”，出栈是“先取值再移指针”；空栈 `top == base - 1`，满栈 `top - base == stacksize`。

### 链栈

链栈是用链式存储结构实现的栈，本质是**只能在表头进行插入和删除的单链表**，因此插入、删除都落在栈顶，指针修改即可，不需要移动元素。

```c
typedef struct StackNode {
    SElemType data;
    struct StackNode *next;
} StackNode, *LinkStack;

LinkStack S;   // S 即栈顶指针，指向栈顶结点
```

结构要点：

- **无头结点**，`S` 直接指向栈顶结点（相当于单链表的头指针指向首元结点）；再加头结点反而多一层跳转，操作更麻烦。
- 结点 $a_n$ 的 `next` 指向 $a_{n-1}$，即**指针方向与元素入栈顺序相反**（每个结点指向栈中位于它下面的元素）。因为操作全在栈顶，这样指最方便。
- **空栈**：`S == NULL`（栈顶指针为空）。
- 只要内存还有空间就不会栈满，**不存在上溢**，也就不需要判满。

**入栈**：生成新结点，填入数据，让其 `next` 指向原栈顶，再让栈顶指针指向它。

```c
Status Push(LinkStack &S, SElemType e) {
    StackNode *p = new StackNode;
    p->data = e;
    p->next = S;   // 原栈顶成为新结点的后继
    S = p;         // 栈顶指针移到新结点
    return OK;
}
```

**出栈**：判空 → 取出栈顶数据 → 暂存栈顶结点 → 栈顶指针后移 → 释放原栈顶结点。

```c
Status Pop(LinkStack &S, SElemType &e) {
    if (S == NULL) return ERROR;
    e = S->data;
    LinkStack p = S;
    S = S->next;
    delete p;
    return OK;
}
```

**取栈顶元素**：判空后直接返回 `S->data`，栈顶指针不动。

链栈的入栈、出栈都只改指针、不含循环，时间开销 $O(1)$；`p->next = S; S = p;` 两步顺序不能颠倒，否则丢失原栈顶。

<figure class="cpd-figure not-content" id="wz-w2-fig-3">
  <svg viewBox="0 0 700 256" role="img" aria-label="链栈无头结点结构及 Push 入栈、Pop 出栈指针修改步骤">
    <defs>
      <marker id="wz-w2-arr-3" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="18" y="16" width="326" height="224" rx="8"/>
    <rect class="fig-box-subtle" x="358" y="16" width="324" height="224" rx="8"/>
    <path class="fig-line-dashed" d="M 62 118 L 154 118" marker-end="url(#wz-w2-arr-3)"/>
    <path class="fig-line" stroke="var(--sl-color-green)" stroke-width="1.6" d="M 62 104 Q 76 72 114 72" marker-end="url(#wz-w2-arr-3)"/>
    <path class="fig-line" stroke="var(--sl-color-accent)" stroke-width="1.6" d="M 184 72 Q 214 72 214 102" marker-end="url(#wz-w2-arr-3)"/>
    <line class="fig-line" stroke="var(--sl-color-blue)" stroke-width="1.4" x1="202" y1="138" x2="202" y2="160" marker-end="url(#wz-w2-arr-3)"/>
    <line class="fig-line" stroke="var(--sl-color-blue)" stroke-width="1.4" x1="202" y1="192" x2="202" y2="212"/>
    <line class="fig-line" stroke="var(--sl-color-red)" stroke-width="1.5" x1="406" y1="74" x2="466" y2="74" marker-end="url(#wz-w2-arr-3)"/>
    <path class="fig-line-dashed" d="M 406 122 L 466 84"/>
    <line class="fig-line" stroke="var(--sl-color-green)" stroke-width="1.6" x1="406" y1="130" x2="466" y2="130" marker-end="url(#wz-w2-arr-3)"/>
    <line class="fig-line" stroke="var(--sl-color-blue)" stroke-width="1.4" x1="518" y1="90" x2="518" y2="112" marker-end="url(#wz-w2-arr-3)"/>
    <line class="fig-line" stroke="var(--sl-color-blue)" stroke-width="1.4" x1="518" y1="146" x2="518" y2="168" marker-end="url(#wz-w2-arr-3)"/>
    <rect class="fig-box-purple" x="30" y="100" width="34" height="28" rx="4"/>
    <rect class="fig-box-green" x="118" y="56" width="44" height="30" rx="3"/>
    <rect class="fig-box-green" x="162" y="56" width="38" height="30" rx="3"/>
    <rect class="fig-box-blue" x="158" y="106" width="44" height="30" rx="3"/>
    <rect class="fig-box-blue" x="202" y="106" width="38" height="30" rx="3"/>
    <rect class="fig-box-blue" x="158" y="162" width="44" height="30" rx="3"/>
    <rect class="fig-box-blue" x="202" y="162" width="38" height="30" rx="3"/>
    <rect class="fig-box" x="252" y="106" width="80" height="86" rx="5"/>
    <rect class="fig-box-orange" x="372" y="60" width="34" height="28" rx="4"/>
    <rect class="fig-box-purple" x="372" y="116" width="34" height="28" rx="4"/>
    <rect class="fig-box-red" x="470" y="60" width="48" height="30" rx="3"/>
    <rect class="fig-box-red" x="518" y="60" width="38" height="30" rx="3"/>
    <rect class="fig-box-blue" x="470" y="116" width="48" height="30" rx="3"/>
    <rect class="fig-box-blue" x="518" y="116" width="38" height="30" rx="3"/>
    <rect class="fig-box-blue" x="470" y="170" width="48" height="30" rx="3"/>
    <rect class="fig-box-blue" x="518" y="170" width="38" height="30" rx="3"/>
    <rect class="fig-box" x="568" y="60" width="102" height="140" rx="5"/>
    <text class="fig-title" x="181" y="36" text-anchor="middle" font-size="12.5">链栈入栈 Push(&amp;S, x)（无头结点）</text>
    <text class="fig-purple" x="47" y="118" text-anchor="middle" font-size="12">S</text>
    <text class="fig-green" x="92" y="64" text-anchor="middle" font-size="10.5">② S = p</text>
    <text class="fig-accent" x="256" y="76" font-size="10.5">① p-&gt;next = S</text>
    <text class="fig-green" x="140" y="75" text-anchor="middle" font-size="11.5">x (p)</text>
    <text class="fig-green" x="181" y="75" text-anchor="middle" font-size="11">•</text>
    <text class="fig-blue" x="180" y="125" text-anchor="middle" font-size="11.5">a₂</text>
    <text class="fig-blue" x="221" y="125" text-anchor="middle" font-size="11">•</text>
    <text class="fig-blue" x="180" y="181" text-anchor="middle" font-size="11.5">a₁</text>
    <text class="fig-muted" x="221" y="181" text-anchor="middle" font-size="10.5">∧</text>
    <text class="fig-muted" x="202" y="226" text-anchor="middle" font-size="10.5">NULL（栈底）</text>
    <text class="fig-label" x="292" y="126" text-anchor="middle" font-size="10.5">指针向下指</text>
    <text class="fig-muted" x="292" y="144" text-anchor="middle" font-size="10">与入栈次序</text>
    <text class="fig-muted" x="292" y="160" text-anchor="middle" font-size="10">正好相反</text>
    <text class="fig-red" x="292" y="178" text-anchor="middle" font-size="10">①②不可逆</text>
    <text class="fig-title" x="520" y="36" text-anchor="middle" font-size="12.5">链栈出栈 Pop(&amp;S, &amp;e)（表头删除）</text>
    <text class="fig-orange" x="389" y="78" text-anchor="middle" font-size="11.5">p</text>
    <text class="fig-purple" x="389" y="134" text-anchor="middle" font-size="11.5">S</text>
    <text class="fig-orange" x="438" y="68" text-anchor="middle" font-size="10">① p=S</text>
    <text class="fig-green" x="438" y="144" text-anchor="middle" font-size="10">② S=S-&gt;next</text>
    <text class="fig-red" x="494" y="79" text-anchor="middle" font-size="11.5">a₃</text>
    <text class="fig-red" x="537" y="79" text-anchor="middle" font-size="11">•</text>
    <text class="fig-blue" x="494" y="135" text-anchor="middle" font-size="11.5">a₂</text>
    <text class="fig-blue" x="537" y="135" text-anchor="middle" font-size="11">•</text>
    <text class="fig-blue" x="494" y="189" text-anchor="middle" font-size="11.5">a₁</text>
    <text class="fig-muted" x="537" y="189" text-anchor="middle" font-size="10.5">∧</text>
    <text class="fig-red" x="619" y="82" text-anchor="middle" font-size="10.5">③ delete p</text>
    <text class="fig-label" x="619" y="106" text-anchor="middle" font-size="10.5">空栈判据：</text>
    <text class="fig-purple" x="619" y="122" text-anchor="middle" font-size="11">S == NULL</text>
    <text class="fig-green" x="619" y="148" text-anchor="middle" font-size="10.5">动态申请结点</text>
    <text class="fig-green" x="619" y="164" text-anchor="middle" font-size="10.5">无上溢风险</text>
    <text class="fig-muted" x="619" y="184" text-anchor="middle" font-size="10">时间均 O(1)</text>
    <text class="fig-muted" x="520" y="224" text-anchor="middle" font-size="11">无头结点直接以 S 指向首元（栈顶），省去额外跳转</text>
  </svg>
  <figcaption>链栈存储与操作机制：无头结点，next 指针自栈顶向栈底串联，Push 与 Pop 均在表头 O(1) 完成</figcaption>
</figure>

> **交互演示**：[顺序栈 / 链栈 / 共享栈](/lab/chapter-3/#lab-arrayStack)

### 栈与递归

**递归**：一个对象的部分包含它自身（用自己定义自己），或一个函数/过程直接或间接调用自身。

- 递归的对象：单链表（指针域指向自身类型）、树（子树仍是树）、广义表（元素可以是广义表）。
- 递归的函数：直接或间接调用自身，如阶乘：$f(0)=1$；$n>0$ 时 $f(n)=n\cdot f(n-1)$。

常用递归的三类场合：① 数学函数本身递归定义（阶乘、Fibonacci 数列）；② 数据结构本身具有递归特性（二叉树、广义表）；③ 问题的求解过程可递归描述（迷宫、汉诺塔）。

递归是**分治法**的一种。用分治法求解需满足三个条件：

1. 大问题能转化为一个新的小问题，且两者解法相同或类同，处理对象的变化有规律；
2. 转化后的新问题更简单、更易求解，可继续转化；
3. 存在可直接求解的边界，即**递归出口**。

对应的程序结构：满足结束条件时直接求解（**基本项**），否则用更小规模的参数调用自身（**归纳项**）。

**函数调用与栈的关系**：调用函数时系统需完成——把实参值传给形参、保存返回地址、为形参和局部变量分配存储区、把控制权转给被调函数；返回时保存运算结果、释放被调函数的局部变量区、按返回地址回到调用处。嵌套调用遵循“**后调用先返回**”，正是后进先出，因此系统用一个**栈**来管理这些信息。

**递归工作栈**中每条工作记录保存：实参、局部变量、返回地址。

| 层次 | 实参 | 返回地址 |
| --- | --- | --- |
| main 调用 f(4) | 4 | r₁ |
| f(4) 调用 f(3) | 3 | r₂ |
| f(3) 调用 f(2) | 2 | r₃ |
| f(2) 调用 f(1) | 1 | r₄ |
| f(1) 调用 f(0) | 0 | r₅ |

求 $4!$ 时逐层深入直到 $f(0)=1$，再逐层出栈回归：$1\times1=1$、$2\times1=2$、$3\times2=6$、$4\times6=24$。最后被调用的最先返回，最先调用的最后返回。

<figure class="cpd-figure not-content" id="wz-w2-fig-4">
  <svg viewBox="0 0 700 278" role="img" aria-label="计算 4! 时递归工作栈的活动记录压栈递推与出栈回归全过程">
    <defs>
      <marker id="wz-w2-arr-4" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="18" y="16" width="444" height="246" rx="8"/>
    <rect class="fig-box-subtle" x="476" y="16" width="206" height="246" rx="8"/>
    <path class="fig-line" stroke="var(--sl-color-blue)" stroke-width="1.6" d="M 64 218 L 64 66" marker-end="url(#wz-w2-arr-4)"/>
    <path class="fig-line" stroke="var(--sl-color-green)" stroke-width="1.5" d="M 308 68 L 336 68 L 336 104 L 310 104" marker-end="url(#wz-w2-arr-4)"/>
    <path class="fig-line" stroke="var(--sl-color-green)" stroke-width="1.5" d="M 308 108 L 336 108 L 336 142 L 310 142" marker-end="url(#wz-w2-arr-4)"/>
    <path class="fig-line" stroke="var(--sl-color-green)" stroke-width="1.5" d="M 308 146 L 336 146 L 336 180 L 310 180" marker-end="url(#wz-w2-arr-4)"/>
    <path class="fig-line" stroke="var(--sl-color-green)" stroke-width="1.5" d="M 308 184 L 336 184 L 336 218 L 310 218" marker-end="url(#wz-w2-arr-4)"/>
    <rect class="fig-box-green" x="108" y="52" width="198" height="32" rx="4"/>
    <rect class="fig-box-blue" x="108" y="90" width="198" height="32" rx="4"/>
    <rect class="fig-box-blue" x="108" y="128" width="198" height="32" rx="4"/>
    <rect class="fig-box-blue" x="108" y="166" width="198" height="32" rx="4"/>
    <rect class="fig-box-accent" x="108" y="204" width="198" height="32" rx="4"/>
    <rect class="fig-box-purple" x="494" y="54" width="170" height="32" rx="4"/>
    <rect class="fig-box-blue" x="494" y="90" width="170" height="32" rx="4"/>
    <rect class="fig-box-orange" x="494" y="126" width="170" height="32" rx="4"/>
    <rect class="fig-box" x="494" y="170" width="170" height="76" rx="5"/>
    <text class="fig-title" x="240" y="36" text-anchor="middle" font-size="12.5">递归工作栈求解 f(4) = 4! 的压栈与回归轨迹</text>
    <text class="fig-blue" x="56" y="136" text-anchor="end" font-size="11">① 递推</text>
    <text class="fig-blue" x="56" y="152" text-anchor="end" font-size="10.5">逐层入栈</text>
    <text class="fig-green" x="207" y="72" text-anchor="middle" font-size="11.5">f(0)：n = 0, ret = r₅（栈顶）</text>
    <text class="fig-blue" x="207" y="110" text-anchor="middle" font-size="11.5">f(1)：n = 1, ret = r₄</text>
    <text class="fig-blue" x="207" y="148" text-anchor="middle" font-size="11.5">f(2)：n = 2, ret = r₃</text>
    <text class="fig-blue" x="207" y="186" text-anchor="middle" font-size="11.5">f(3)：n = 3, ret = r₂</text>
    <text class="fig-accent" x="207" y="224" text-anchor="middle" font-size="11.5">f(4)：n = 4, ret = r₁（栈底）</text>
    <text class="fig-green" x="346" y="72" font-size="11">出口返 1</text>
    <text class="fig-green" x="346" y="110" font-size="11">1 × 1 = 1</text>
    <text class="fig-green" x="346" y="148" font-size="11">2 × 1 = 2</text>
    <text class="fig-green" x="346" y="186" font-size="11">3 × 2 = 6</text>
    <text class="fig-accent" x="346" y="224" font-size="11.5">4 × 6 = 24</text>
    <text class="fig-muted" x="240" y="252" text-anchor="middle" font-size="10.5">② 触达递归出口 f(0)=1 后按返回地址 r₅→r₁ 逆序弹栈计算</text>
    <text class="fig-title" x="579" y="36" text-anchor="middle" font-size="12.5">单条工作记录（栈帧）</text>
    <text class="fig-purple" x="579" y="74" text-anchor="middle" font-size="11.5">调用实参（如 n）</text>
    <text class="fig-blue" x="579" y="110" text-anchor="middle" font-size="11.5">函数局部变量区</text>
    <text class="fig-orange" x="579" y="146" text-anchor="middle" font-size="11.5">返回地址 rᵢ</text>
    <text class="fig-label" x="579" y="190" text-anchor="middle" font-size="11">空间复杂度 = O(递归深度)</text>
    <text class="fig-muted" x="579" y="208" text-anchor="middle" font-size="10.5">后调用者必先返回</text>
    <text class="fig-muted" x="579" y="224" text-anchor="middle" font-size="10.5">尾递归可直接改写为循环</text>
    <text class="fig-muted" x="579" y="240" text-anchor="middle" font-size="10.5">将空间由 O(n) 降至 O(1)</text>
  </svg>
  <figcaption>递归工作栈运行原理：每次调用压入“实参 + 局部变量 + 返回地址”栈帧，出口触发后逆序出栈回代</figcaption>
</figure>

递归的优缺点：

- 优点：结构清晰、程序易读，二叉树等算法中尤其简洁；
- 缺点：每次调用都要生成工作记录并入栈，返回时出栈，**时间和空间开销都大**。

转非递归的两条思路：① **尾递归 / 单向递归**（如 Fibonacci 的两次调用只依赖主调函数参数）可改写为循环结构；② 自己设计一个栈模拟系统栈，按递归执行过程手工维护。后者结构不清晰、可读性差，通常只在时间效率要求高时才做。

> **★考点**：为什么递归必须用栈——函数调用满足“后调用先返回”，与栈的 LIFO 一致；递归工作栈记录实参、局部变量和返回地址。

<figure class="cpd-figure not-content" id="wz-w2-fig-5">
  <svg viewBox="0 0 700 264" role="img" aria-label="双栈法算术表达式求值 OPND 与 OPTR 协同过程及后缀表达式转换">
    <defs>
      <marker id="wz-w2-arr-5" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="18" y="16" width="352" height="232" rx="8"/>
    <rect class="fig-box-subtle" x="384" y="16" width="298" height="232" rx="8"/>
    <line class="fig-line" stroke="var(--sl-color-gray-4)" stroke-width="2" x1="48" y1="80" x2="48" y2="196"/>
    <line class="fig-line" stroke="var(--sl-color-gray-4)" stroke-width="2" x1="126" y1="80" x2="126" y2="196"/>
    <line class="fig-line" stroke="var(--sl-color-gray-4)" stroke-width="2.4" x1="46" y1="196" x2="128" y2="196"/>
    <line class="fig-line" stroke="var(--sl-color-gray-4)" stroke-width="2" x1="168" y1="80" x2="168" y2="196"/>
    <line class="fig-line" stroke="var(--sl-color-gray-4)" stroke-width="2" x1="246" y1="80" x2="246" y2="196"/>
    <line class="fig-line" stroke="var(--sl-color-gray-4)" stroke-width="2.4" x1="166" y1="196" x2="248" y2="196"/>
    <path class="fig-line" stroke="var(--sl-color-orange)" stroke-width="1.5" d="M 128 100 L 266 100" marker-end="url(#wz-w2-arr-5)"/>
    <path class="fig-line" stroke="var(--sl-color-orange)" stroke-width="1.5" d="M 248 96 L 266 96"/>
    <path class="fig-line" stroke="var(--sl-color-green)" stroke-width="1.5" d="M 310 140 L 310 172 L 132 172" marker-end="url(#wz-w2-arr-5)"/>
    <rect class="fig-box-orange" x="54" y="88" width="66" height="26" rx="3"/>
    <rect class="fig-box-orange" x="54" y="116" width="66" height="26" rx="3"/>
    <rect class="fig-box-blue" x="54" y="144" width="66" height="24" rx="3"/>
    <rect class="fig-box-blue" x="54" y="170" width="66" height="24" rx="3"/>
    <rect class="fig-box-orange" x="174" y="88" width="66" height="26" rx="3"/>
    <rect class="fig-box-purple" x="174" y="116" width="66" height="26" rx="3"/>
    <rect class="fig-box-purple" x="174" y="144" width="66" height="24" rx="3"/>
    <rect class="fig-box-purple" x="174" y="170" width="66" height="24" rx="3"/>
    <rect class="fig-box-green" x="268" y="82" width="88" height="58" rx="5"/>
    <rect class="fig-box" x="400" y="50" width="266" height="40" rx="4"/>
    <rect class="fig-box-blue" x="400" y="98" width="266" height="44" rx="4"/>
    <rect class="fig-box-accent" x="400" y="150" width="266" height="84" rx="5"/>
    <text class="fig-title" x="194" y="36" text-anchor="middle" font-size="12.5">栈的经典应用：双栈求值 3 + 2 × (6 − 4)</text>
    <text class="fig-muted" x="194" y="56" text-anchor="middle" font-size="11">扫描至“)”触发弹栈归约瞬间</text>
    <text class="fig-orange" x="87" y="105" text-anchor="middle" font-size="11.5">4 (b)</text>
    <text class="fig-orange" x="87" y="133" text-anchor="middle" font-size="11.5">6 (a)</text>
    <text class="fig-blue" x="87" y="160" text-anchor="middle" font-size="11.5">2</text>
    <text class="fig-blue" x="87" y="186" text-anchor="middle" font-size="11.5">3</text>
    <text class="fig-label" x="87" y="214" text-anchor="middle" font-size="11">OPND 数栈</text>
    <text class="fig-muted" x="87" y="232" text-anchor="middle" font-size="10">注意次序 a−b</text>
    <text class="fig-orange" x="207" y="105" text-anchor="middle" font-size="12">−</text>
    <text class="fig-purple" x="207" y="133" text-anchor="middle" font-size="12">(</text>
    <text class="fig-purple" x="207" y="160" text-anchor="middle" font-size="12">×</text>
    <text class="fig-purple" x="207" y="186" text-anchor="middle" font-size="12">+</text>
    <text class="fig-label" x="207" y="214" text-anchor="middle" font-size="11">OPTR 符栈</text>
    <text class="fig-muted" x="207" y="232" text-anchor="middle" font-size="10">底垫 # 定界</text>
    <text class="fig-green" x="312" y="102" text-anchor="middle" font-size="11">6 − 4 = 2</text>
    <text class="fig-green" x="312" y="120" text-anchor="middle" font-size="10.5">结果压回</text>
    <text class="fig-green" x="312" y="134" text-anchor="middle" font-size="10.5">OPND</text>
    <text class="fig-muted" x="312" y="192" text-anchor="middle" font-size="10">再算 2×2=4</text>
    <text class="fig-accent" x="312" y="208" text-anchor="middle" font-size="10.5">终得 3+4=7</text>
    <text class="fig-title" x="533" y="36" text-anchor="middle" font-size="12.5">408 中缀转后缀与后缀求值口诀</text>
    <text class="fig-label" x="533" y="67" text-anchor="middle" font-size="11">中缀：3 + 2 × ( 6 − 4 )</text>
    <text class="fig-green" x="533" y="83" text-anchor="middle" font-size="11">后缀（逆波兰）：3  2  6  4  −  ×  +</text>
    <text class="fig-blue" x="533" y="116" text-anchor="middle" font-size="11">中缀→后缀：仅用 1 个运算符栈</text>
    <text class="fig-muted" x="533" y="133" text-anchor="middle" font-size="10.5">遇到高/同级栈顶先弹出，左括号入栈、右括号弹至(</text>
    <text class="fig-accent" x="533" y="170" text-anchor="middle" font-size="11">后缀表达式求值：仅用 1 个操作数栈</text>
    <text class="fig-label" x="533" y="188" text-anchor="middle" font-size="10.5">① 遇操作数直接入栈；② 遇二元符连续 Pop 两次</text>
    <text class="fig-red" x="533" y="206" text-anchor="middle" font-size="10.5">★ 先弹出的是右操作数 b，后弹出的是左操作数 a</text>
    <text class="fig-muted" x="533" y="223" text-anchor="middle" font-size="10.5">减法 a − b、除法 a / b 顺序绝不可颠倒！</text>
  </svg>
  <figcaption>栈在表达式处理中的核心模式：双栈直接求值中缀式，单栈转换/求值后缀式（注意右操作数先出栈）</figcaption>
</figure>

> **交互演示**：[括号匹配 / 表达式求值 / 递归调用栈](/lab/chapter-3/#lab-brackets)

### 队列的定义与先进先出

**队列（queue）**：只允许在**表尾插入**、在**表头删除**的线性表，即“**头删尾插**”。允许插入的一端称**队尾（rear）**，允许删除的一端称**队头（front）**。用 $Q=(a_1,\dots,a_n)$ 表示，$a_1$ 为队头元素，$a_n$ 为队尾元素。

- **入队**（enqueue）：在队尾插入元素；
- **出队**（dequeue）：删除队头元素。

特性为**先进先出**（FIFO，First In First Out），元素按入队先后顺序出队。逻辑结构仍是一对一线性关系，存储结构也有顺序队列与链队列，其中**顺序存储的循环队列**最常用。

典型应用（凡是有“排队使用有限资源”的地方）：脱机打印（多台机器把打印任务排到一台打印机）、多用户分时系统的优先级队列、实时系统按信号到达顺序处理、网络报文按到达时间先后传输。

**队列的抽象数据类型**：与栈高度对称。

```
ADT Queue {
  数据对象：D = { a_i | a_i ∈ ElemSet, i = 1,…,n, n ≥ 0 }
  数据关系：R = { <a_{i-1}, a_i> }   // a_1 为队头，a_n 为队尾
  基本操作：
    InitQueue(&Q)      初始化空队列
    DestroyQueue(&Q)   销毁：释放全部存储空间
    ClearQueue(&Q)     清空：保留队列对象，元素清掉
    QueueEmpty(Q)      判空
    QueueLength(Q)     返回元素个数
    GetHead(Q, &e)     用 e 返回队头元素（不出队）
    EnQueue(&Q, e)     入队：插入到队尾
    DeQueue(&Q, &e)    出队：删除队头元素，值由 e 返回
} ADT Queue
```

`GetHead` 与 `DeQueue` 都取队头元素，区别是前者不修改队列、队头指针不动。

### 顺序队列与假溢出

顺序队列用数组存放元素，另设两个整数下标：

```c
typedef struct {
    QElemType *base;   // 动态分配的数组，base 指向首元素
    int front;         // 队头元素的下标
    int rear;          // 队尾元素之后（下一个可插入位置）的下标
} SqQueue;
```

数组容量由符号常量 `MAXQSIZE`（如 100）指定，入队、出队与判满、求长都要用它取模。

初始 `front = rear = 0`，表示空队列。入队：`Q.base[Q.rear] = e; Q.rear++;`；出队：`e = Q.base[Q.front]; Q.front++;`。

**队空**判据：`front == rear`。出队时 $front$ 不断后移，数组前部空出的单元无法再被使用。

**假溢出**：`rear == MAXQSIZE` 时数组下标越界，但队列并未真正满。分两种情况：

| 情形 | 判定 | 性质 |
| --- | --- | --- |
| 真溢出 | `front == 0` 且 `rear == MAXQSIZE` | 全部单元已用，确实满了 |
| 假溢出 | `front > 0` 且 `rear == MAXQSIZE` | 前面有空单元，只是不能用 |

解决假溢出的朴素办法是每次出队后把剩余元素整体前移，但每出队一次要移动几乎全部元素，时间效率太差。正确做法是把数组看作**首尾相接的环**——`rear` 加 1 到 `MAXQSIZE` 时回绕到 0，用**取模运算**实现：

```c
Q.rear = (Q.rear + 1) % MAXQSIZE;
```

> **注意**：循环队列并不是真的把存储空间变成圆形，只是用取模让下标回绕，从而重复利用已出队腾出的单元。

<figure class="cpd-figure not-content" id="wz-w2-fig-6">
  <svg viewBox="0 0 700 248" role="img" aria-label="顺序队列从初始空队到假溢出，再通过取模运算回绕为循环队列的演进过程">
    <defs>
      <marker id="wz-w2-arr-6" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="18" y="16" width="204" height="216" rx="8"/>
    <rect class="fig-box-subtle" x="236" y="16" width="228" height="216" rx="8"/>
    <rect class="fig-box-subtle" x="478" y="16" width="204" height="216" rx="8"/>
    <line class="fig-line" stroke="var(--sl-color-accent)" stroke-width="1.5" x1="46" y1="68" x2="46" y2="96" marker-end="url(#wz-w2-arr-6)"/>
    <line class="fig-line" stroke="var(--sl-color-accent)" stroke-width="1.5" x1="330" y1="68" x2="330" y2="96" marker-end="url(#wz-w2-arr-6)"/>
    <line class="fig-line" stroke="var(--sl-color-red)" stroke-width="1.5" x1="438" y1="68" x2="438" y2="96" marker-end="url(#wz-w2-arr-6)"/>
    <line class="fig-line" stroke="var(--sl-color-accent)" stroke-width="1.5" x1="564" y1="68" x2="564" y2="96" marker-end="url(#wz-w2-arr-6)"/>
    <path class="fig-line" stroke="var(--sl-color-green)" stroke-width="1.6" d="M 656 116 C 674 116 674 168 580 168 C 512 168 510 154 510 136" marker-end="url(#wz-w2-arr-6)"/>
    <rect class="fig-box" x="32" y="100" width="28" height="32"/>
    <rect class="fig-box" x="60" y="100" width="28" height="32"/>
    <rect class="fig-box" x="88" y="100" width="28" height="32"/>
    <rect class="fig-box" x="116" y="100" width="28" height="32"/>
    <rect class="fig-box" x="144" y="100" width="28" height="32"/>
    <rect class="fig-box" x="172" y="100" width="28" height="32"/>
    <rect class="fig-box-dashed" x="260" y="100" width="28" height="32"/>
    <rect class="fig-box-dashed" x="288" y="100" width="28" height="32"/>
    <rect class="fig-box-blue" x="316" y="100" width="28" height="32"/>
    <rect class="fig-box-blue" x="344" y="100" width="28" height="32"/>
    <rect class="fig-box-blue" x="372" y="100" width="28" height="32"/>
    <rect class="fig-box-blue" x="400" y="100" width="28" height="32"/>
    <rect class="fig-box-red" x="428" y="100" width="24" height="32"/>
    <rect class="fig-box-green" x="494" y="100" width="28" height="32"/>
    <rect class="fig-box" x="522" y="100" width="28" height="32"/>
    <rect class="fig-box-blue" x="550" y="100" width="28" height="32"/>
    <rect class="fig-box-blue" x="578" y="100" width="28" height="32"/>
    <rect class="fig-box-blue" x="606" y="100" width="28" height="32"/>
    <rect class="fig-box-blue" x="634" y="100" width="28" height="32"/>
    <text class="fig-title" x="120" y="38" text-anchor="middle" font-size="12">① 初始空队（MAXQSIZE=6）</text>
    <text class="fig-accent" x="68" y="62" text-anchor="middle" font-size="10.5">front=rear=0</text>
    <text class="fig-muted" x="46" y="146" text-anchor="middle" font-size="10">0</text>
    <text class="fig-muted" x="74" y="146" text-anchor="middle" font-size="10">1</text>
    <text class="fig-muted" x="102" y="146" text-anchor="middle" font-size="10">2</text>
    <text class="fig-muted" x="130" y="146" text-anchor="middle" font-size="10">3</text>
    <text class="fig-muted" x="158" y="146" text-anchor="middle" font-size="10">4</text>
    <text class="fig-muted" x="186" y="146" text-anchor="middle" font-size="10">5</text>
    <text class="fig-label" x="120" y="180" text-anchor="middle" font-size="11">队空：front == rear</text>
    <text class="fig-muted" x="120" y="200" text-anchor="middle" font-size="10.5">入队 rear++，出队 front++</text>
    <text class="fig-title" x="350" y="38" text-anchor="middle" font-size="12">② 假溢出（front=2, rear=6）</text>
    <text class="fig-accent" x="330" y="62" text-anchor="middle" font-size="10.5">front=2</text>
    <text class="fig-red" x="432" y="62" text-anchor="middle" font-size="10.5">rear=6!</text>
    <text class="fig-orange" x="274" y="120" text-anchor="middle" font-size="10">闲</text>
    <text class="fig-orange" x="302" y="120" text-anchor="middle" font-size="10">闲</text>
    <text class="fig-blue" x="330" y="120" text-anchor="middle" font-size="11">a₃</text>
    <text class="fig-blue" x="358" y="120" text-anchor="middle" font-size="11">a₄</text>
    <text class="fig-blue" x="386" y="120" text-anchor="middle" font-size="11">a₅</text>
    <text class="fig-blue" x="414" y="120" text-anchor="middle" font-size="11">a₆</text>
    <text class="fig-red" x="440" y="120" text-anchor="middle" font-size="10">越</text>
    <text class="fig-muted" x="274" y="146" text-anchor="middle" font-size="10">0</text>
    <text class="fig-muted" x="302" y="146" text-anchor="middle" font-size="10">1</text>
    <text class="fig-muted" x="330" y="146" text-anchor="middle" font-size="10">2</text>
    <text class="fig-muted" x="358" y="146" text-anchor="middle" font-size="10">3</text>
    <text class="fig-muted" x="386" y="146" text-anchor="middle" font-size="10">4</text>
    <text class="fig-muted" x="414" y="146" text-anchor="middle" font-size="10">5</text>
    <text class="fig-red" x="350" y="180" text-anchor="middle" font-size="11">front &gt; 0 且 rear == MAXQSIZE</text>
    <text class="fig-muted" x="350" y="200" text-anchor="middle" font-size="10.5">0、1 号空着却无法继续入队</text>
    <text class="fig-title" x="580" y="38" text-anchor="middle" font-size="12">③ 取模回绕复用低端单元</text>
    <text class="fig-accent" x="564" y="62" text-anchor="middle" font-size="10.5">front=2</text>
    <text class="fig-green" x="508" y="120" text-anchor="middle" font-size="11">a₇</text>
    <text class="fig-muted" x="536" y="120" text-anchor="middle" font-size="10">空</text>
    <text class="fig-blue" x="564" y="120" text-anchor="middle" font-size="11">a₃</text>
    <text class="fig-blue" x="592" y="120" text-anchor="middle" font-size="11">a₄</text>
    <text class="fig-blue" x="620" y="120" text-anchor="middle" font-size="11">a₅</text>
    <text class="fig-blue" x="648" y="120" text-anchor="middle" font-size="11">a₆</text>
    <text class="fig-green" x="580" y="186" text-anchor="middle" font-size="11">rear = (rear + 1) % 6 → 0</text>
    <text class="fig-muted" x="580" y="204" text-anchor="middle" font-size="10.5">逻辑首尾相接，消除搬移开销</text>
  </svg>
  <figcaption>顺序队列假溢出的成因与解法：出队腾出的低端空间通过取模回绕（% MAXQSIZE）在 O(1) 时间内循环复用</figcaption>
</figure>

### 循环队列的队空、队满与长度

下标回绕带来了新问题：队满时 $rear$ 也会绕回与 $front$ 相等，与队空无法区分。有三种区分办法：① 增设标志位（记录上次操作是入队还是出队）；② 另设计数器 `count` 记录元素个数；③ **少用一个元素空间**（牺牲一个单元，课程采用）。

牺牲一个单元的含义：$rear$ 所指的单元始终不存数据，队满时“$rear$ 再前进一步就会追上 $front$”。此时实际容量只有 `MAXQSIZE - 1`。三个公式如下：

$$
\text{队空：}\quad front == rear
$$

$$
\text{队满：}\quad (rear + 1) \bmod \text{MAXQSIZE} == front
$$

$$
\text{队列长度：}\quad (rear - front + \text{MAXQSIZE}) \bmod \text{MAXQSIZE}
$$

解释：

- **队空**：两下标指向同一位置，队列中没有元素。
- **队满**：$rear$ 的下一个位置就是 $front$，说明两者之间只剩那个被牺牲的空单元。以 `MAXQSIZE = 6`、`front = 2`、`rear = 1` 为例，$(1+1)\bmod 6=2=front$ 成立，此时只存了下标 2、3、4、5、0 共 5 个元素。
- **长度**：若 $rear \ge front$，直接相减即可；若 $rear < front$（$rear$ 已绕回低端），相减为负数，需先加 `MAXQSIZE` 再取模。如 `MAXQSIZE = 6`、`front = 4`、`rear = 0`：$(0-4+6)\bmod 6=2$，正确；若不用取模则得 $-4$，显然不是元素个数。

<figure class="cpd-figure not-content" id="wz-fig-9">
  <svg viewBox="0 0 700 288" role="img" aria-label="循环队列空队与牺牲一格满队对比及三种判满方案">
    <defs>
      <marker id="wz-arr-9" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="18" y="16" width="322" height="256" rx="8"/>
    <rect class="fig-box-subtle" x="354" y="16" width="328" height="256" rx="8"/>
    <circle class="fig-line-dashed" cx="179" cy="118" r="58"/>
    <circle class="fig-line-dashed" cx="518" cy="118" r="58"/>
    <line class="fig-line" stroke="var(--sl-color-accent)" stroke-width="1.5" x1="82" y1="84" x2="108" y2="88" marker-end="url(#wz-arr-9)"/>
    <line class="fig-line" stroke="var(--sl-color-orange)" stroke-width="1.5" x1="82" y1="98" x2="108" y2="94" marker-end="url(#wz-arr-9)"/>
    <line class="fig-line" stroke="var(--sl-color-accent)" stroke-width="1.5" x1="418" y1="89" x2="446" y2="89" marker-end="url(#wz-arr-9)"/>
    <line class="fig-line" stroke="var(--sl-color-orange)" stroke-width="1.5" x1="418" y1="147" x2="446" y2="147" marker-end="url(#wz-arr-9)"/>
    <circle class="fig-box" cx="179" cy="176" r="18"/>
    <circle class="fig-box" cx="129" cy="147" r="18"/>
    <circle class="fig-box" cx="129" cy="89" r="18"/>
    <circle class="fig-box" cx="179" cy="60" r="18"/>
    <circle class="fig-box" cx="229" cy="89" r="18"/>
    <circle class="fig-box" cx="229" cy="147" r="18"/>
    <rect class="fig-box" x="32" y="202" width="294" height="58" rx="5"/>
    <circle class="fig-box-blue" cx="518" cy="176" r="18"/>
    <circle class="fig-box-dashed" cx="468" cy="147" r="18"/>
    <circle class="fig-box-green" cx="468" cy="89" r="18"/>
    <circle class="fig-box-blue" cx="518" cy="60" r="18"/>
    <circle class="fig-box-blue" cx="568" cy="89" r="18"/>
    <circle class="fig-box-blue" cx="568" cy="147" r="18"/>
    <rect class="fig-box-accent" x="368" y="202" width="300" height="58" rx="5"/>
    <text class="fig-title" x="179" y="36" text-anchor="middle" font-size="12.5">① 队空：front == rear（如均指 2）</text>
    <text class="fig-accent" x="78" y="85" text-anchor="end" font-size="10.5">front=2</text>
    <text class="fig-orange" x="78" y="102" text-anchor="end" font-size="10.5">rear=2</text>
    <text class="fig-muted" x="179" y="180" text-anchor="middle" font-size="11">0</text>
    <text class="fig-muted" x="129" y="151" text-anchor="middle" font-size="11">1</text>
    <text class="fig-label" x="129" y="93" text-anchor="middle" font-size="11">2</text>
    <text class="fig-muted" x="179" y="64" text-anchor="middle" font-size="11">3</text>
    <text class="fig-muted" x="229" y="93" text-anchor="middle" font-size="11">4</text>
    <text class="fig-muted" x="229" y="151" text-anchor="middle" font-size="11">5</text>
    <text class="fig-label" x="179" y="220" text-anchor="middle" font-size="11">三种区分队空/队满方案（MAXQSIZE = M）：</text>
    <text class="fig-muted" x="179" y="236" text-anchor="middle" font-size="10.5">方案A：牺牲一格（存 M−1 个）· 方案B：设 size 计数</text>
    <text class="fig-muted" x="179" y="251" text-anchor="middle" font-size="10.5">方案C：设 tag（入队置 1，出队置 0，相等时看 tag）</text>
    <text class="fig-title" x="518" y="36" text-anchor="middle" font-size="12.5">② 队满：牺牲下标 1 空单元（存 5 个）</text>
    <text class="fig-accent" x="414" y="93" text-anchor="end" font-size="11">front=2</text>
    <text class="fig-orange" x="414" y="151" text-anchor="end" font-size="11">rear=1</text>
    <text class="fig-blue" x="518" y="180" text-anchor="middle" font-size="11">0:e</text>
    <text class="fig-orange" x="468" y="151" text-anchor="middle" font-size="10.5">1:空</text>
    <text class="fig-green" x="468" y="93" text-anchor="middle" font-size="11">2:a</text>
    <text class="fig-blue" x="518" y="64" text-anchor="middle" font-size="11">3:b</text>
    <text class="fig-blue" x="568" y="93" text-anchor="middle" font-size="11">4:c</text>
    <text class="fig-blue" x="568" y="151" text-anchor="middle" font-size="11">5:d</text>
    <text class="fig-muted" x="626" y="122" text-anchor="middle" font-size="10.5">顺时针入队</text>
    <text class="fig-accent" x="518" y="220" text-anchor="middle" font-size="11.5">队满：(rear + 1) % 6 == front（(1+1)%6 == 2）</text>
    <text class="fig-label" x="518" y="238" text-anchor="middle" font-size="11">通用队长 = (rear − front + M) % M = (1−2+6)%6 = 5</text>
    <text class="fig-muted" x="518" y="253" text-anchor="middle" font-size="10">rear 永远指向下一个待写空位，不可存数据</text>
  </svg>
  <figcaption>循环队列空满判据对比：牺牲 1 个单元使队满满足 (rear + 1) % MAXQSIZE == front，与队空 front == rear 彻底分离</figcaption>
</figure>

> **★考点**：三个公式必须区分“取模”与“不取模”。判断队满不能写 `rear + 1 == front`（漏掉取模），否则 `rear == MAXQSIZE - 1` 时的回绕情形会漏判；求长度不能写 `rear - front`，否则绕回后为负。凡是下标加减，一律对 `MAXQSIZE` 取模。

### 循环队列的基本操作

**初始化**（算法 3.11）：为数组分配 `MAXQSIZE` 个单元，判分配失败，两下标清零。

```c
Status InitQueue(SqQueue &Q) {
    Q.base = new QElemType[MAXQSIZE];
    if (!Q.base) exit(OVERFLOW);
    Q.front = Q.rear = 0;      // 空队列
    return OK;
}
```

**求队长**：`return (Q.rear - Q.front + MAXQSIZE) % MAXQSIZE;`

**入队**（算法 3.13）：先按队满条件判满，再存到 $rear$ 所指单元，最后 $rear$ 取模后移。

```c
Status EnQueue(SqQueue &Q, QElemType e) {
    if ((Q.rear + 1) % MAXQSIZE == Q.front) return ERROR;  // 队满
    Q.base[Q.rear] = e;
    Q.rear = (Q.rear + 1) % MAXQSIZE;
    return OK;
}
```

**出队**：先判空，取出 $front$ 所指元素，$front$ 取模后移。

```c
Status DeQueue(SqQueue &Q, QElemType &e) {
    if (Q.front == Q.rear) return ERROR;   // 队空
    e = Q.base[Q.front];
    Q.front = (Q.front + 1) % MAXQSIZE;
    return OK;
}
```

**取队头元素**（算法 3.15）：判空后直接返回 `Q.base[Q.front]`，`front` 不动，元素仍留在队列中——这是它与出队的唯一区别。

> **注意**：`Q.base[Q.rear] = e` 必须写在 `Q.rear` 更新之前；出队时先把值取出再移动 `front`。顺序颠倒会丢元素或取错元素。

**过程拆解**（`MAXQSIZE=8`，初始 `front=6`、`rear=3`，队列中已有下标 6、7、0、1、2 共 5 个元素）：

| 操作 | 动作 | 结果 |
|:---:|:---|:---|
| 入队 `x` | 先写 `data[3]=x`，再 `rear=(3+1)%8=4` | 元素 6 个，`front=6, rear=4` |
| 出队 | 先取 `e=data[6]`，再 `front=(6+1)%8=7` | 元素 5 个，`front=7, rear=4` |
| 再入队 `y` | 写 `data[4]=y`，`rear=(4+1)%8=5` | 元素 6 个，`front=7, rear=5` |

> **注意**：入队先写后移 `rear`，出队先取后移 `front`；指针一到数组末尾就取模回绕。

<figure class="cpd-figure not-content" id="wz-w2-fig-7">
  <svg viewBox="0 0 700 236" role="img" aria-label="MAXQSIZE=8 循环队列跨界回绕入队与出队三步下标追踪">
    <defs>
      <marker id="wz-w2-arr-7" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="18" y="16" width="664" height="204" rx="8"/>
    <line class="fig-line" stroke="var(--sl-color-gray-4)" stroke-width="1.4" x1="168" y1="74" x2="212" y2="74" marker-end="url(#wz-w2-arr-7)"/>
    <line class="fig-line" stroke="var(--sl-color-gray-4)" stroke-width="1.4" x1="168" y1="122" x2="212" y2="122" marker-end="url(#wz-w2-arr-7)"/>
    <line class="fig-line" stroke="var(--sl-color-gray-4)" stroke-width="1.4" x1="168" y1="170" x2="212" y2="170" marker-end="url(#wz-w2-arr-7)"/>
    <rect class="fig-box" x="32" y="58" width="132" height="32" rx="4"/>
    <rect class="fig-box-green" x="32" y="106" width="132" height="32" rx="4"/>
    <rect class="fig-box-orange" x="32" y="154" width="132" height="32" rx="4"/>
    <rect class="fig-box-blue" x="218" y="58" width="42" height="32"/><rect class="fig-box-blue" x="260" y="58" width="42" height="32"/><rect class="fig-box-blue" x="302" y="58" width="42" height="32"/><rect class="fig-box-dashed" x="344" y="58" width="42" height="32"/><rect class="fig-box" x="386" y="58" width="42" height="32"/><rect class="fig-box" x="428" y="58" width="42" height="32"/><rect class="fig-box-accent" x="470" y="58" width="42" height="32"/><rect class="fig-box-blue" x="512" y="58" width="42" height="32"/>
    <rect class="fig-box-blue" x="218" y="106" width="42" height="32"/><rect class="fig-box-blue" x="260" y="106" width="42" height="32"/><rect class="fig-box-blue" x="302" y="106" width="42" height="32"/><rect class="fig-box-green" x="344" y="106" width="42" height="32"/><rect class="fig-box-dashed" x="386" y="106" width="42" height="32"/><rect class="fig-box" x="428" y="106" width="42" height="32"/><rect class="fig-box-accent" x="470" y="106" width="42" height="32"/><rect class="fig-box-blue" x="512" y="106" width="42" height="32"/>
    <rect class="fig-box-blue" x="218" y="154" width="42" height="32"/><rect class="fig-box-blue" x="260" y="154" width="42" height="32"/><rect class="fig-box-blue" x="302" y="154" width="42" height="32"/><rect class="fig-box-blue" x="344" y="154" width="42" height="32"/><rect class="fig-box-green" x="386" y="154" width="42" height="32"/><rect class="fig-box-dashed" x="428" y="154" width="42" height="32"/><rect class="fig-box" x="470" y="154" width="42" height="32"/><rect class="fig-box-accent" x="512" y="154" width="42" height="32"/>
    <text class="fig-title" x="350" y="36" text-anchor="middle" font-size="12.5">循环队列回绕状态追踪（MAXQSIZE = 8，已绕过右端回到 0..2）</text>
    <text class="fig-muted" x="239" y="52" text-anchor="middle" font-size="10">[0]</text><text class="fig-muted" x="281" y="52" text-anchor="middle" font-size="10">[1]</text><text class="fig-muted" x="323" y="52" text-anchor="middle" font-size="10">[2]</text><text class="fig-muted" x="365" y="52" text-anchor="middle" font-size="10">[3]</text><text class="fig-muted" x="407" y="52" text-anchor="middle" font-size="10">[4]</text><text class="fig-muted" x="449" y="52" text-anchor="middle" font-size="10">[5]</text><text class="fig-muted" x="491" y="52" text-anchor="middle" font-size="10">[6]</text><text class="fig-muted" x="533" y="52" text-anchor="middle" font-size="10">[7]</text>
    <text class="fig-label" x="98" y="78" text-anchor="middle" font-size="11">初始：f=6, r=3</text>
    <text class="fig-green" x="98" y="126" text-anchor="middle" font-size="11">① 入队 x</text>
    <text class="fig-orange" x="98" y="174" text-anchor="middle" font-size="11">② 出队 + 入 y</text>
    <text class="fig-blue" x="239" y="78" text-anchor="middle" font-size="11">c</text><text class="fig-blue" x="281" y="78" text-anchor="middle" font-size="11">d</text><text class="fig-blue" x="323" y="78" text-anchor="middle" font-size="11">e</text><text class="fig-orange" x="365" y="78" text-anchor="middle" font-size="10.5">r=3</text><text class="fig-muted" x="407" y="78" text-anchor="middle" font-size="10">空</text><text class="fig-muted" x="449" y="78" text-anchor="middle" font-size="10">空</text><text class="fig-accent" x="491" y="78" text-anchor="middle" font-size="10.5">a(f)</text><text class="fig-blue" x="533" y="78" text-anchor="middle" font-size="11">b</text>
    <text class="fig-muted" x="618" y="78" text-anchor="middle" font-size="10.5">长 (3−6+8)%8 = 5</text>
    <text class="fig-blue" x="239" y="126" text-anchor="middle" font-size="11">c</text><text class="fig-blue" x="281" y="126" text-anchor="middle" font-size="11">d</text><text class="fig-blue" x="323" y="126" text-anchor="middle" font-size="11">e</text><text class="fig-green" x="365" y="126" text-anchor="middle" font-size="11">x</text><text class="fig-orange" x="407" y="126" text-anchor="middle" font-size="10.5">r=4</text><text class="fig-muted" x="449" y="126" text-anchor="middle" font-size="10">空</text><text class="fig-accent" x="491" y="126" text-anchor="middle" font-size="10.5">a(f)</text><text class="fig-blue" x="533" y="126" text-anchor="middle" font-size="11">b</text>
    <text class="fig-green" x="618" y="126" text-anchor="middle" font-size="10.5">长 (4−6+8)%8 = 6</text>
    <text class="fig-blue" x="239" y="174" text-anchor="middle" font-size="11">c</text><text class="fig-blue" x="281" y="174" text-anchor="middle" font-size="11">d</text><text class="fig-blue" x="323" y="174" text-anchor="middle" font-size="11">e</text><text class="fig-blue" x="365" y="174" text-anchor="middle" font-size="11">x</text><text class="fig-green" x="407" y="174" text-anchor="middle" font-size="11">y</text><text class="fig-orange" x="449" y="174" text-anchor="middle" font-size="10.5">r=5</text><text class="fig-muted" x="491" y="174" text-anchor="middle" font-size="10">已出</text><text class="fig-accent" x="533" y="174" text-anchor="middle" font-size="10.5">b(f)</text>
    <text class="fig-orange" x="618" y="174" text-anchor="middle" font-size="10.5">f=7, r=5, 长 = 6</text>
    <text class="fig-muted" x="350" y="206" text-anchor="middle" font-size="11">入队：先写 base[rear]=e 再 rear=(rear+1)%8；出队：先读 base[front] 再 front=(front+1)%8</text>
  </svg>
  <figcaption>循环队列跨界状态演化：有效元素跨越下标 [6..7] 与 [0..4] 两段，取模公式统一求出真实队长</figcaption>
</figure>

> **交互演示**：[循环队列三种判空/判满实现](/lab/chapter-3/#lab-queue_spare)

### 链队列

链队列用链表存储队列，无需连续空间，长度可随元素增减，只要内存足够就不会队满，也不存在假溢出问题。为便于在队尾插入，采用**带头结点**的单链表，并用两个指针组成一个结构：

```c
typedef struct QNode {
    QElemType data;
    struct QNode *next;
} QNode, *QueuePtr;

typedef struct {
    QueuePtr front;   // 头指针，指向头结点
    QueuePtr rear;    // 尾指针，指向队尾结点
} LinkQueue;
```

- **空队列**：`Q.front == Q.rear`，即两个指针都指向头结点，且 `Q.front->next == NULL`。头结点不存数据。
- 入队只能在队尾，出队只能在队头（头结点之后的首元结点）。
- 访问成员用 `Q.front`、`Q.rear`（结构体变量用点号，不是箭头）。

**初始化**：分配一个头结点，`front`、`rear` 都指向它，并令 `next = NULL`。

**入队**：在尾结点之后接新结点，再让 `rear` 指向新结点。

```c
Status EnQueue(LinkQueue &Q, QElemType e) {
    QueuePtr p = new QNode;
    p->data = e;
    p->next = NULL;
    Q.rear->next = p;   // 接到原队尾之后
    Q.rear = p;         // 新结点成为新队尾
    return OK;
}
```

**出队**：删除头结点之后的首元结点。

```c
Status DeQueue(LinkQueue &Q, QElemType &e) {
    if (Q.front == Q.rear) return ERROR;   // 队空
    QueuePtr p = Q.front->next;
    e = p->data;
    Q.front->next = p->next;
    if (Q.rear == p) Q.rear = Q.front;     // 删除的是最后一个结点
    delete p;
    return OK;
}
```

> **★考点**：出队时若被删结点恰好是队尾结点，删除后队列变空，必须把 `rear` 重新指向头结点（`Q.rear = Q.front`），否则 `rear` 悬空，后续入队会写到已释放的空间。

<figure class="cpd-figure not-content" id="wz-w2-fig-8">
  <svg viewBox="0 0 700 256" role="img" aria-label="带头结点链队列的队尾入队与删除最后一个结点时 rear 归位操作">
    <defs>
      <marker id="wz-w2-arr-8" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="18" y="16" width="328" height="224" rx="8"/>
    <rect class="fig-box-subtle" x="358" y="16" width="324" height="224" rx="8"/>
    <line class="fig-line" stroke="var(--sl-color-accent)" stroke-width="1.5" x1="58" y1="68" x2="58" y2="100" marker-end="url(#wz-w2-arr-8)"/>
    <line class="fig-line" stroke="var(--sl-color-blue)" stroke-width="1.4" x1="88" y1="118" x2="112" y2="118" marker-end="url(#wz-w2-arr-8)"/>
    <line class="fig-line" stroke="var(--sl-color-blue)" stroke-width="1.4" x1="176" y1="118" x2="200" y2="118" marker-end="url(#wz-w2-arr-8)"/>
    <path class="fig-line-dashed" d="M 224 68 L 224 100" marker-end="url(#wz-w2-arr-8)"/>
    <line class="fig-line" stroke="var(--sl-color-green)" stroke-width="1.5" x1="264" y1="118" x2="282" y2="118" marker-end="url(#wz-w2-arr-8)"/>
    <path class="fig-line" stroke="var(--sl-color-green)" stroke-width="1.5" d="M 238 58 Q 306 58 306 100" marker-end="url(#wz-w2-arr-8)"/>
    <line class="fig-line" stroke="var(--sl-color-accent)" stroke-width="1.5" x1="412" y1="68" x2="412" y2="100" marker-end="url(#wz-w2-arr-8)"/>
    <path class="fig-line-dashed" d="M 444 118 L 516 118"/>
    <path class="fig-line-dashed" d="M 550 68 L 550 100" marker-end="url(#wz-w2-arr-8)"/>
    <path class="fig-line" stroke="var(--sl-color-red)" stroke-width="1.7" d="M 532 58 Q 434 58 428 100" marker-end="url(#wz-w2-arr-8)"/>
    <rect class="fig-box-purple" x="34" y="44" width="48" height="24" rx="4"/>
    <rect class="fig-box-orange" x="196" y="44" width="48" height="24" rx="4"/>
    <rect class="fig-box" x="32" y="104" width="34" height="28" rx="3"/><rect class="fig-box" x="66" y="104" width="22" height="28" rx="3"/>
    <rect class="fig-box-blue" x="116" y="104" width="38" height="28" rx="3"/><rect class="fig-box-blue" x="154" y="104" width="22" height="28" rx="3"/>
    <rect class="fig-box-blue" x="204" y="104" width="38" height="28" rx="3"/><rect class="fig-box-blue" x="242" y="104" width="22" height="28" rx="3"/>
    <rect class="fig-box-green" x="286" y="104" width="32" height="28" rx="3"/><rect class="fig-box-green" x="318" y="104" width="18" height="28" rx="3"/>
    <rect class="fig-box" x="32" y="152" width="300" height="74" rx="5"/>
    <rect class="fig-box-purple" x="388" y="44" width="48" height="24" rx="4"/>
    <rect class="fig-box-orange" x="526" y="44" width="48" height="24" rx="4"/>
    <rect class="fig-box" x="386" y="104" width="36" height="28" rx="3"/><rect class="fig-box" x="422" y="104" width="24" height="28" rx="3"/>
    <rect class="fig-box-red" x="520" y="104" width="42" height="28" rx="3"/><rect class="fig-box-red" x="562" y="104" width="24" height="28" rx="3"/>
    <rect class="fig-box-red" x="372" y="148" width="296" height="78" rx="5"/>
    <text class="fig-title" x="182" y="34" text-anchor="middle" font-size="12">链队列队尾入队 EnQueue（带头结点）</text>
    <text class="fig-purple" x="58" y="60" text-anchor="middle" font-size="10.5">Q.front</text>
    <text class="fig-orange" x="220" y="60" text-anchor="middle" font-size="10.5">Q.rear</text>
    <text class="fig-green" x="286" y="54" text-anchor="middle" font-size="10">② rear=p</text>
    <text class="fig-muted" x="49" y="122" text-anchor="middle" font-size="10">头</text><text class="fig-muted" x="77" y="122" text-anchor="middle" font-size="10">•</text>
    <text class="fig-blue" x="135" y="122" text-anchor="middle" font-size="11">a₁</text><text class="fig-blue" x="165" y="122" text-anchor="middle" font-size="10">•</text>
    <text class="fig-blue" x="223" y="122" text-anchor="middle" font-size="11">a₂</text><text class="fig-blue" x="253" y="122" text-anchor="middle" font-size="10">•</text>
    <text class="fig-green" x="302" y="122" text-anchor="middle" font-size="11">x(p)</text><text class="fig-green" x="327" y="122" text-anchor="middle" font-size="9.5">∧</text>
    <text class="fig-green" x="275" y="143" text-anchor="middle" font-size="9.5">① rear-&gt;next=p</text>
    <text class="fig-label" x="182" y="172" text-anchor="middle" font-size="11">空队列特征：Q.front == Q.rear（均指头结点）</text>
    <text class="fig-muted" x="182" y="190" text-anchor="middle" font-size="10.5">带头结点使空队与非空队的入队代码完全统一</text>
    <text class="fig-muted" x="182" y="208" text-anchor="middle" font-size="10.5">入队、出队均仅改常数个指针，时间复杂度 O(1)</text>
    <text class="fig-title" x="520" y="34" text-anchor="middle" font-size="12">★ 易错边界：删除唯一结点 p 出队</text>
    <text class="fig-purple" x="412" y="60" text-anchor="middle" font-size="10.5">Q.front</text>
    <text class="fig-orange" x="550" y="60" text-anchor="middle" font-size="10.5">Q.rear</text>
    <text class="fig-red" x="478" y="54" text-anchor="middle" font-size="10">② Q.rear = Q.front</text>
    <text class="fig-muted" x="404" y="122" text-anchor="middle" font-size="10">头</text><text class="fig-accent" x="434" y="122" text-anchor="middle" font-size="10">∧</text>
    <text class="fig-red" x="541" y="122" text-anchor="middle" font-size="11">a₁(p)</text><text class="fig-red" x="574" y="122" text-anchor="middle" font-size="10">∧</text>
    <text class="fig-muted" x="482" y="112" text-anchor="middle" font-size="9.5">① front-&gt;next=NULL</text>
    <text class="fig-red" x="626" y="122" text-anchor="middle" font-size="10">③ delete p</text>
    <text class="fig-red" x="520" y="168" text-anchor="middle" font-size="11">if (Q.rear == p) Q.rear = Q.front;</text>
    <text class="fig-label" x="520" y="188" text-anchor="middle" font-size="10.5">若漏写此句，delete p 后 Q.rear 沦为悬空野指针！</text>
    <text class="fig-muted" x="520" y="206" text-anchor="middle" font-size="10.5">删除后队列恢复初始空态（front == rear 指头结点）</text>
  </svg>
  <figcaption>链队列指针维护要点：常规入队改尾指针，但最后一个元素出队变空时必须把 Q.rear 重置回 Q.front</figcaption>
</figure>

**取队头元素**：判空后返回 `Q.front->next->data`。

**销毁**：从头结点起逐个释放；可借用 `rear` 暂存后继，省去额外指针变量。

```c
while (Q.front) {
    Q.rear = Q.front->next;
    delete Q.front;
    Q.front = Q.rear;
}
```

链队列的入队、出队都只修改常数个指针，时间 $O(1)$；增加一个尾指针换取尾部 $O(1)$ 插入的便利，是“按操作需要调整存储结构”的典型例子。

## 第4章 串、数组和广义表

### 串的定义与基本术语

**串（string，字符串）**：由零个或多个任意字符组成的有限序列
$$
S=“a_1a_2\cdots a_n”\qquad (n\ge 0)
$$
其中 $S$ 为**串名**，引号内为**串值**，$n$ 为**串长**。$n=0$ 时称为**空串**，记作 $\varnothing$（与表示空集的符号相同）。

| 术语 | 含义 |
| --- | --- |
| 子串 | 主串中任意个**连续**字符组成的子序列；空串与串自身也是子串 |
| 真子串 | 不含自身的所有子串 |
| 主串 | 包含子串的那个串 |
| 字符位置 | 字符在序列中的序号（从 1 开始编号） |
| 子串位置 | 子串第 1 个字符在主串中的序号 |
| 空格串 | 由若干个空格构成的串，长度 ≥ 1，**不是空串** |
| 串相等 | 长度相等且对应位置字符全部相同；所有空串彼此相等 |

例：`S="bei"`，`T="jing"`，`U="beijing"`，`V="bei jing"`。则 $|S|=3$，$|T|=4$，$|U|=7$，$|V|=8$；`S` 在 `U`、`V` 中的位置都是 1，`T` 在 `U` 中的位置是 4、在 `V` 中的位置是 5（空格占一个字符位）。

串仍是**线性结构**，数据元素之间是一对一的前驱/后继关系；与一般线性表的区别是**内容受限**——每个数据元素只能是字符。数组和广义表则是线性结构的推广（元素本身又可看作线性表），严格说已属非线性结构。

### 串的抽象数据类型与存储结构

**ADT String**：数据对象 $D=\{a_i\mid a_i\in\text{CharSet},\ i=1,\dots,n\}$，数据关系为 $<a_{i-1},a_i>$。基本操作包括赋值、复制、比较、求长、连接、求子串、定位、替换、插入、删除、清空、销毁。

两个串比较按字符的 **ASCII 码逐位比较**：相等返回 0，$S<T$ 返回负值，$S>T$ 返回正值。多数操作在高级语言中已实现；本章重点是定位操作 `Index(S, T, pos)`，即**串的模式匹配**。

**顺序串**——用数组连续存放字符，另设长度域：

```c
#define MAXLEN 255
typedef struct {
    char ch[MAXLEN + 1];   /* 0 号单元闲置，字符存于 ch[1..MAXLEN] */
    int  length;           /* 当前串长 */
} SString;
```

`MAXLEN=255` 时数组共 256 个单元，下标 0–255。字符从 `ch[1]` 开始存放、`ch[0]` 闲置，是为了让“下标”与“第几个字符”一致，便于后续算法。

**链串**：每个结点存 1 个字符 + 1 个 `next` 指针。字符占 1 字节、指针占 4 字节，**存储密度**为
$$
\frac{1}{1+4}=0.2
$$
仅 20%，空间浪费大。

**块链结构**：每个结点存一个字符块，块内字符连续：

```c
#define CHUNKSIZE 80
typedef struct Chunk {
    char ch[CHUNKSIZE];
    struct Chunk *next;
} Chunk;
typedef struct {
    Chunk *head, *tail;   /* 串的头、尾指针 */
    int length;           /* 串长 */
} LString;
```

块内 4 个字符 + 4 字节指针时密度 $4/8=50\%$；块内 50 个字符时密度 $50/54\approx 92\%$。块不必存满，留余量以便插入。

> **注意**：实际应用中**顺序串更常用**——串很少做插入/删除，多是匹配、查找、求子串，顺序存储可直接随机访问且无指针开销。本章算法均基于顺序串。

<figure class="cpd-figure not-content" id="wz-w2-fig-9">
  <svg viewBox="0 0 700 258" role="img" aria-label="顺序串 SString、单字符链串与块链结构 LString 的存储布局与存储密度对比">
    <defs>
      <marker id="wz-w2-arr-9" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="18" y="16" width="664" height="96" rx="8"/>
    <rect class="fig-box-subtle" x="18" y="124" width="318" height="118" rx="8"/>
    <rect class="fig-box-subtle" x="350" y="124" width="332" height="118" rx="8"/>
    <line class="fig-line" stroke="var(--sl-color-blue)" stroke-width="1.4" x1="100" y1="184" x2="124" y2="184" marker-end="url(#wz-w2-arr-9)"/>
    <line class="fig-line" stroke="var(--sl-color-blue)" stroke-width="1.4" x1="192" y1="184" x2="216" y2="184" marker-end="url(#wz-w2-arr-9)"/>
    <line class="fig-line" stroke="var(--sl-color-blue)" stroke-width="1.4" x1="502" y1="184" x2="532" y2="184" marker-end="url(#wz-w2-arr-9)"/>
    <rect class="fig-box-dashed" x="34" y="50" width="46" height="32"/>
    <rect class="fig-box-blue" x="80" y="50" width="38" height="32"/><rect class="fig-box-blue" x="118" y="50" width="38" height="32"/><rect class="fig-box-blue" x="156" y="50" width="38" height="32"/><rect class="fig-box-blue" x="194" y="50" width="38" height="32"/><rect class="fig-box-blue" x="232" y="50" width="38" height="32"/><rect class="fig-box-blue" x="270" y="50" width="38" height="32"/><rect class="fig-box-blue" x="308" y="50" width="38" height="32"/>
    <rect class="fig-box" x="346" y="50" width="46" height="32"/><rect class="fig-box" x="392" y="50" width="54" height="32"/>
    <rect class="fig-box-accent" x="462" y="50" width="96" height="32" rx="4"/>
    <rect class="fig-box-red" x="34" y="168" width="28" height="30"/><rect class="fig-box" x="62" y="168" width="38" height="30"/>
    <rect class="fig-box-red" x="128" y="168" width="28" height="30"/><rect class="fig-box" x="156" y="168" width="36" height="30"/>
    <rect class="fig-box-red" x="220" y="168" width="28" height="30"/><rect class="fig-box" x="248" y="168" width="36" height="30"/>
    <rect class="fig-box-green" x="366" y="168" width="26" height="30"/><rect class="fig-box-green" x="392" y="168" width="26" height="30"/><rect class="fig-box-green" x="418" y="168" width="26" height="30"/><rect class="fig-box-green" x="444" y="168" width="26" height="30"/><rect class="fig-box" x="470" y="168" width="32" height="30"/>
    <rect class="fig-box-green" x="536" y="168" width="26" height="30"/><rect class="fig-box-green" x="562" y="168" width="26" height="30"/><rect class="fig-box-green" x="588" y="168" width="26" height="30"/><rect class="fig-box-dashed" x="614" y="168" width="26" height="30"/><rect class="fig-box" x="640" y="168" width="28" height="30"/>
    <text class="fig-title" x="34" y="36" font-size="12">① 顺序串 SString（ch[0] 闲置，字符位序 1..length 与数组下标严格对齐）</text>
    <text class="fig-muted" x="57" y="70" text-anchor="middle" font-size="10.5">闲置</text>
    <text class="fig-blue" x="99" y="70" text-anchor="middle" font-size="12">b</text><text class="fig-blue" x="137" y="70" text-anchor="middle" font-size="12">e</text><text class="fig-blue" x="175" y="70" text-anchor="middle" font-size="12">i</text><text class="fig-blue" x="213" y="70" text-anchor="middle" font-size="12">j</text><text class="fig-blue" x="251" y="70" text-anchor="middle" font-size="12">i</text><text class="fig-blue" x="289" y="70" text-anchor="middle" font-size="12">n</text><text class="fig-blue" x="327" y="70" text-anchor="middle" font-size="12">g</text>
    <text class="fig-muted" x="369" y="70" text-anchor="middle" font-size="11">…</text><text class="fig-muted" x="419" y="70" text-anchor="middle" font-size="10.5">[255]</text>
    <text class="fig-accent" x="510" y="70" text-anchor="middle" font-size="11.5">length = 7</text>
    <text class="fig-muted" x="57" y="98" text-anchor="middle" font-size="10">[0]</text><text class="fig-muted" x="99" y="98" text-anchor="middle" font-size="10">[1]</text><text class="fig-muted" x="137" y="98" text-anchor="middle" font-size="10">[2]</text><text class="fig-muted" x="175" y="98" text-anchor="middle" font-size="10">[3]</text><text class="fig-muted" x="213" y="98" text-anchor="middle" font-size="10">[4]</text><text class="fig-muted" x="251" y="98" text-anchor="middle" font-size="10">[5]</text><text class="fig-muted" x="289" y="98" text-anchor="middle" font-size="10">[6]</text><text class="fig-muted" x="327" y="98" text-anchor="middle" font-size="10">[7]</text>
    <text class="fig-green" x="622" y="70" text-anchor="middle" font-size="11">存储密度 ≈ 100%</text>
    <text class="fig-muted" x="622" y="90" text-anchor="middle" font-size="10">模式匹配首选</text>
    <text class="fig-title" x="177" y="148" text-anchor="middle" font-size="12">② 单字符链串（1B 字符 + 4B 指针）</text>
    <text class="fig-red" x="48" y="187" text-anchor="middle" font-size="11.5">b</text><text class="fig-muted" x="81" y="187" text-anchor="middle" font-size="10">next</text>
    <text class="fig-red" x="142" y="187" text-anchor="middle" font-size="11.5">e</text><text class="fig-muted" x="174" y="187" text-anchor="middle" font-size="10">next</text>
    <text class="fig-red" x="234" y="187" text-anchor="middle" font-size="11.5">i</text><text class="fig-muted" x="266" y="187" text-anchor="middle" font-size="10">∧</text>
    <text class="fig-red" x="177" y="222" text-anchor="middle" font-size="11">存储密度 = 1 / (1 + 4) = 20%（指针开销过大）</text>
    <text class="fig-title" x="516" y="148" text-anchor="middle" font-size="12">③ 块链结构 LString（每结点存 CHUNKSIZE 字符）</text>
    <text class="fig-green" x="379" y="187" text-anchor="middle" font-size="11">b</text><text class="fig-green" x="405" y="187" text-anchor="middle" font-size="11">e</text><text class="fig-green" x="431" y="187" text-anchor="middle" font-size="11">i</text><text class="fig-green" x="457" y="187" text-anchor="middle" font-size="11">j</text><text class="fig-muted" x="486" y="187" text-anchor="middle" font-size="10">•</text>
    <text class="fig-green" x="549" y="187" text-anchor="middle" font-size="11">i</text><text class="fig-green" x="575" y="187" text-anchor="middle" font-size="11">n</text><text class="fig-green" x="601" y="187" text-anchor="middle" font-size="11">g</text><text class="fig-muted" x="627" y="187" text-anchor="middle" font-size="10.5">#</text><text class="fig-muted" x="654" y="187" text-anchor="middle" font-size="10">∧</text>
    <text class="fig-green" x="516" y="222" text-anchor="middle" font-size="11">4B 块密度 50%；50B 块密度 50/54 ≈ 92.6%（末块填 #）</text>
  </svg>
  <figcaption>串的三种存储结构：顺序串省去指针且下标从 1 起便于匹配；块链串通过增大块容量显著提升存储密度</figcaption>
</figure>

### BF 模式匹配算法

问题：求模式串 $T$（子串）在主串 $S$（目标串/正文串）中**第一次出现的位置**，失败返回 0。

**BF（Brute-Force，简单匹配/暴力破解）思想**：从 $S$ 的 `pos` 位置起，把 $T$ 逐位对齐比较；某位失配就让 $T$ 整体右移一位、从第一个字符重新开始，直到匹配成功或 $S$ 剩余长度不足。

```c
int Index_BF(SString S, SString T, int pos) {
    int i = pos, j = 1;
    while (i <= S.length && j <= T.length) {
        if (S.ch[i] == T.ch[j]) { ++i; ++j; }  /* 继续比较后继字符 */
        else { i = i - j + 2; j = 1; }         /* 失配：主串回溯，模式串复位 */
    }
    if (j > T.length) return i - T.length;     /* j 越界说明 T 全部匹配 */
    return 0;
}
```

两个关键点：

- **回溯位置** $i=i-j+2$。本轮比较起点是 $i-j+1$，下一轮起点即 $i-j+2$；同时 $j$ 复位为 1。
- **成功返回** $i-|T|$。匹配成功时 $i$ 已移到匹配段之后，减去模式串长度即为该子串首字符的序号。

**复杂度**：

- 最好 $O(m)$：第一个起点即全部匹配，只比较 $m$ 个字符。
- 最坏 $(n-m)m+m\to O(nm)$：$S$ 形如 `aaaa…ab`、$T$ 形如 `aaab`，前 $n-m$ 个起点都要比到 $T$ 末位才失配。
- 平均约 $\frac{nm}{2}$，数量级仍是 $O(nm)$。

低效根源：失配后 $i$ 回退、$j$ 归 1，已比较过的信息被丢弃。

<figure class="cpd-figure not-content" id="wz-w2-fig-10">
  <svg viewBox="0 0 700 258" role="img" aria-label="BF 朴素模式匹配算法在最坏情况 S=aaaaab, T=aaab 下的主串指针回溯过程">
    <defs>
      <marker id="wz-w2-arr-10" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="18" y="16" width="430" height="226" rx="8"/>
    <rect class="fig-box-subtle" x="462" y="16" width="220" height="226" rx="8"/>
    <path class="fig-line" stroke="var(--sl-color-red)" stroke-width="1.5" d="M 272 118 C 272 134 196 134 196 142" marker-end="url(#wz-w2-arr-10)"/>
    <path class="fig-line" stroke="var(--sl-color-red)" stroke-width="1.5" d="M 310 166 C 310 182 234 182 234 190" marker-end="url(#wz-w2-arr-10)"/>
    <rect class="fig-box" x="140" y="54" width="38" height="28"/><rect class="fig-box" x="178" y="54" width="38" height="28"/><rect class="fig-box" x="216" y="54" width="38" height="28"/><rect class="fig-box" x="254" y="54" width="38" height="28"/><rect class="fig-box" x="292" y="54" width="38" height="28"/><rect class="fig-box" x="330" y="54" width="38" height="28"/>
    <rect class="fig-box-blue" x="140" y="92" width="38" height="26"/><rect class="fig-box-blue" x="178" y="92" width="38" height="26"/><rect class="fig-box-blue" x="216" y="92" width="38" height="26"/><rect class="fig-box-red" x="254" y="92" width="38" height="26"/>
    <rect class="fig-box-blue" x="178" y="144" width="38" height="24"/><rect class="fig-box-blue" x="216" y="144" width="38" height="24"/><rect class="fig-box-blue" x="254" y="144" width="38" height="24"/><rect class="fig-box-red" x="292" y="144" width="38" height="24"/>
    <rect class="fig-box-green" x="216" y="192" width="38" height="26"/><rect class="fig-box-green" x="254" y="192" width="38" height="26"/><rect class="fig-box-green" x="292" y="192" width="38" height="26"/><rect class="fig-box-green" x="330" y="192" width="38" height="26"/>
    <rect class="fig-box-orange" x="476" y="50" width="192" height="54" rx="5"/>
    <rect class="fig-box-green" x="476" y="114" width="192" height="50" rx="5"/>
    <rect class="fig-box" x="476" y="174" width="192" height="54" rx="5"/>
    <text class="fig-title" x="233" y="36" text-anchor="middle" font-size="12.5">BF 最坏情况指针回溯追踪（S =“aaaaab”, T =“aaab”）</text>
    <text class="fig-muted" x="159" y="48" text-anchor="middle" font-size="10">1</text><text class="fig-muted" x="197" y="48" text-anchor="middle" font-size="10">2</text><text class="fig-muted" x="235" y="48" text-anchor="middle" font-size="10">3</text><text class="fig-muted" x="273" y="48" text-anchor="middle" font-size="10">4</text><text class="fig-muted" x="311" y="48" text-anchor="middle" font-size="10">5</text><text class="fig-muted" x="349" y="48" text-anchor="middle" font-size="10">6</text>
    <text class="fig-label" x="82" y="72" text-anchor="middle" font-size="11.5">主串 S</text>
    <text class="fig-label" x="159" y="73" text-anchor="middle" font-size="12">a</text><text class="fig-label" x="197" y="73" text-anchor="middle" font-size="12">a</text><text class="fig-label" x="235" y="73" text-anchor="middle" font-size="12">a</text><text class="fig-label" x="273" y="73" text-anchor="middle" font-size="12">a</text><text class="fig-label" x="311" y="73" text-anchor="middle" font-size="12">a</text><text class="fig-label" x="349" y="73" text-anchor="middle" font-size="12">b</text>
    <text class="fig-muted" x="82" y="109" text-anchor="middle" font-size="11">第 1 趟</text>
    <text class="fig-blue" x="159" y="109" text-anchor="middle" font-size="11.5">a</text><text class="fig-blue" x="197" y="109" text-anchor="middle" font-size="11.5">a</text><text class="fig-blue" x="235" y="109" text-anchor="middle" font-size="11.5">a</text><text class="fig-red" x="273" y="109" text-anchor="middle" font-size="11.5">b✗</text>
    <text class="fig-red" x="364" y="110" font-size="10.5">i: 4→2, j→1</text>
    <text class="fig-muted" x="82" y="160" text-anchor="middle" font-size="11">第 2 趟</text>
    <text class="fig-blue" x="197" y="160" text-anchor="middle" font-size="11.5">a</text><text class="fig-blue" x="235" y="160" text-anchor="middle" font-size="11.5">a</text><text class="fig-blue" x="273" y="160" text-anchor="middle" font-size="11.5">a</text><text class="fig-red" x="311" y="160" text-anchor="middle" font-size="11.5">b✗</text>
    <text class="fig-red" x="378" y="160" font-size="10.5">i: 5→3, j→1</text>
    <text class="fig-green" x="82" y="209" text-anchor="middle" font-size="11">第 3 趟</text>
    <text class="fig-green" x="235" y="209" text-anchor="middle" font-size="11.5">a✓</text><text class="fig-green" x="273" y="209" text-anchor="middle" font-size="11.5">a✓</text><text class="fig-green" x="311" y="209" text-anchor="middle" font-size="11.5">a✓</text><text class="fig-green" x="349" y="209" text-anchor="middle" font-size="11.5">b✓</text>
    <text class="fig-green" x="404" y="209" text-anchor="middle" font-size="10.5">成功！</text>
    <text class="fig-title" x="572" y="36" text-anchor="middle" font-size="12">BF 核心下标公式</text>
    <text class="fig-orange" x="572" y="70" text-anchor="middle" font-size="11.5">失配回溯：i = i − j + 2</text>
    <text class="fig-muted" x="572" y="90" text-anchor="middle" font-size="10.5">本趟起点 i−j+1，下趟右移 1 位</text>
    <text class="fig-green" x="572" y="134" text-anchor="middle" font-size="11.5">成功返回：i − T.length</text>
    <text class="fig-muted" x="572" y="152" text-anchor="middle" font-size="10.5">如 i=7, m=4 → 首字符位序 3</text>
    <text class="fig-label" x="572" y="194" text-anchor="middle" font-size="11">最坏比较 (n−m+1)·m 次</text>
    <text class="fig-red" x="572" y="214" text-anchor="middle" font-size="11">时间复杂度 O(n·m)</text>
  </svg>
  <figcaption>BF 算法回溯瓶颈：每次在模式串末尾失配时，主串指针 i 均被迫倒退至 i − j + 2 重头再比</figcaption>
</figure>

### KMP 算法的思想

由 Knuth、Morris、Pratt 提出。两条改进：

1. **主串指针 $i$ 不回溯**，只单向前进；
2. 失配时 $j$ 不退到 1，而是退到 `next[j]`，即把模式串右滑到“已匹配后缀 = 某前缀”的位置。

原理：失配时必有 $S[i-j+1..i-1]=T[1..j-1]$。若 $T[1..j-1]$ 存在长度为 $r$ 的相等真前缀与真后缀，则该后缀已经与 $T$ 的前 $r$ 个字符相同，可直接把 $T$ 的第 $r+1$ 个字符对准当前 $i$，这 $r$ 个字符无须重比。

**next 的定义**（下标从 1 起）：

| 情况 | $next[j]$ |
| --- | --- |
| $j=1$ | $0$（规定） |
| $j=2$ | $1$（规定） |
| $j\ge 3$ | 前 $j-1$ 个字符的最长相等前后缀长度 $+\,1$（找不到相等前后缀时为 $1$） |

即 $next[j]$ = 前 $j-1$ 个字符中**最长相等真前缀与真后缀的长度 + 1**。$next$ 只与模式串有关，与主串无关。

```c
int Index_KMP(SString S, SString T, int pos) {
    int i = pos, j = 1;
    while (i <= S.length && j <= T.length) {
        if (j == 0 || S.ch[i] == T.ch[j]) { ++i; ++j; }
        else j = next[j];          /* i 不动，模式串右滑 */
    }
    if (j > T.length) return i - T.length;
    return 0;
}
```

`j == 0` 表示已退到 `next[1]=0`：当前 $i$ 位置不可能匹配，$i$ 前进一位、$j$ 回到 1。

<figure class="cpd-figure not-content" id="wz-fig-kmp">
  <svg viewBox="0 0 700 292" role="img" aria-label="KMP 模式匹配主循环控制流程图">
    <defs>
      <marker id="wz-arr-kmp" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="18" y="10" width="664" height="272" rx="8"/>
    <line class="fig-line" stroke="var(--sl-color-gray-4)" stroke-width="1.4" x1="154" y1="42" x2="204" y2="42" marker-end="url(#wz-arr-kmp)"/>
    <line class="fig-line" stroke="var(--sl-color-green)" stroke-width="1.4" x1="316" y1="68" x2="316" y2="100" marker-end="url(#wz-arr-kmp)"/>
    <line class="fig-line" stroke="var(--sl-color-orange)" stroke-width="1.4" x1="424" y1="42" x2="484" y2="42" marker-end="url(#wz-arr-kmp)"/>
    <path class="fig-line-dashed" stroke="var(--sl-color-orange)" stroke-width="1.3" d="M 574 62 L 574 84 L 360 84 L 360 60" marker-end="url(#wz-arr-kmp)"/>
    <line class="fig-line" stroke="var(--sl-color-gray-4)" stroke-width="1.4" x1="316" y1="138" x2="316" y2="160" marker-end="url(#wz-arr-kmp)"/>
    <line class="fig-line" stroke="var(--sl-color-green)" stroke-width="1.4" x1="410" y1="188" x2="474" y2="188" marker-end="url(#wz-arr-kmp)"/>
    <line class="fig-line" stroke="var(--sl-color-gray-4)" stroke-width="1.4" x1="316" y1="212" x2="316" y2="230" marker-end="url(#wz-arr-kmp)"/>
    <line class="fig-line" stroke="var(--sl-color-red)" stroke-width="1.4" x1="410" y1="254" x2="474" y2="254" marker-end="url(#wz-arr-kmp)"/>
    <path class="fig-line" stroke="var(--sl-color-gray-4)" stroke-width="1.3" d="M 222 254 L 136 254 L 136 58 L 236 58" marker-end="url(#wz-arr-kmp)"/>
    <rect class="fig-box-accent" x="30" y="24" width="124" height="36" rx="6"/>
    <polygon class="fig-box-blue" points="316,16 424,42 316,68 208,42"/>
    <rect class="fig-box-orange" x="488" y="22" width="176" height="40" rx="6"/>
    <rect class="fig-box-green" x="252" y="104" width="128" height="34" rx="6"/>
    <polygon class="fig-box" points="316,164 410,188 316,212 222,188"/>
    <rect class="fig-box-green" x="478" y="170" width="188" height="36" rx="6"/>
    <polygon class="fig-box" points="316,232 410,254 316,276 222,254"/>
    <rect class="fig-box-red" x="478" y="236" width="188" height="36" rx="6"/>
    <text class="fig-accent" x="92" y="46" text-anchor="middle" font-size="12">i = pos, j = 1</text>
    <text class="fig-blue" x="316" y="46" text-anchor="middle" font-size="11.5">j == 0 或 S[i] == T[j] ?</text>
    <text class="fig-green" x="328" y="88" font-size="11">是</text>
    <text class="fig-orange" x="456" y="34" text-anchor="middle" font-size="11">否（失配）</text>
    <text class="fig-orange" x="576" y="46" text-anchor="middle" font-size="12">j = next[j]，i 不动</text>
    <text class="fig-green" x="316" y="125" text-anchor="middle" font-size="12">++i, ++j</text>
    <text class="fig-label" x="316" y="192" text-anchor="middle" font-size="11.5">j &gt; T.length ?</text>
    <text class="fig-green" x="444" y="180" text-anchor="middle" font-size="11">是</text>
    <text class="fig-green" x="572" y="192" text-anchor="middle" font-size="11.5">返回 i − T.length（成功）</text>
    <text class="fig-muted" x="328" y="225" font-size="11">否</text>
    <text class="fig-label" x="316" y="258" text-anchor="middle" font-size="11.5">i &gt; S.length ?</text>
    <text class="fig-red" x="444" y="246" text-anchor="middle" font-size="11">是</text>
    <text class="fig-red" x="572" y="258" text-anchor="middle" font-size="11.5">返回 0（匹配失败）</text>
    <text class="fig-muted" x="126" y="160" text-anchor="end" font-size="11">否（继续）</text>
  </svg>
  <figcaption>KMP 主循环流程图：匹配时双指针同进，失配时仅模式串指针 j 跳至 next[j]，主串指针 i 永不回退</figcaption>
</figure>

**过程拆解**：$S=\texttt{abababaa}$，$T=\texttt{ababaa}$，`next`$=[0,1,1,2,3,4]$。

| 步骤 | $i$ | $j$ | 比较 | 动作 |
|:---:|:---:|:---:|:---|:---|
| 1 | 1～5 | 1～5 | `ababa` 全部相等 | $i=6,j=6$ |
| 2 | 6 | 6 | $S_6=b \ne T_6=a$ | 失配，$j=next[6]=4$ |
| 3 | 6 | 4 | $S_6=b = T_4=b$ | 匹配，$i=7,j=5$ |
| 4 | 7 | 5 | $S_7=a = T_5=a$ | 匹配，$i=8,j=6$ |
| 5 | 8 | 6 | $S_8=a = T_6=a$ | 匹配，$j=7>T.length$，成功 |

起点为 $i-j+1=9-6=3$，即 $S[3..8]=\texttt{ababaa}$。失配时主串指针 $i$ 始终没有回退。

<figure class="cpd-figure not-content" id="wz-w2-fig-11">
  <svg viewBox="0 0 700 248" role="img" aria-label="KMP 算法在 S=abababaa, T=ababaa 中失配右滑对齐与主串指针 i 不回溯追踪">
    <defs>
      <marker id="wz-w2-arr-11" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="18" y="16" width="664" height="216" rx="8"/>
    <line class="fig-line-dashed" stroke="var(--sl-color-accent)" stroke-width="1.5" x1="331" y1="54" x2="331" y2="196"/>
    <path class="fig-line" stroke="var(--sl-color-orange)" stroke-width="1.5" d="M 159 138 L 235 138" marker-end="url(#wz-w2-arr-11)"/>
    <rect class="fig-box" x="122" y="54" width="38" height="28"/><rect class="fig-box" x="160" y="54" width="38" height="28"/><rect class="fig-box-green" x="198" y="54" width="38" height="28"/><rect class="fig-box-green" x="236" y="54" width="38" height="28"/><rect class="fig-box-green" x="274" y="54" width="38" height="28"/><rect class="fig-box-accent" x="312" y="54" width="38" height="28"/><rect class="fig-box" x="350" y="54" width="38" height="28"/><rect class="fig-box" x="388" y="54" width="38" height="28"/>
    <rect class="fig-box-blue" x="122" y="96" width="38" height="28"/><rect class="fig-box-blue" x="160" y="96" width="38" height="28"/><rect class="fig-box-green" x="198" y="96" width="38" height="28"/><rect class="fig-box-green" x="236" y="96" width="38" height="28"/><rect class="fig-box-green" x="274" y="96" width="38" height="28"/><rect class="fig-box-red" x="312" y="96" width="38" height="28"/>
    <rect class="fig-box-green" x="198" y="152" width="38" height="28"/><rect class="fig-box-green" x="236" y="152" width="38" height="28"/><rect class="fig-box-green" x="274" y="152" width="38" height="28"/><rect class="fig-box-accent" x="312" y="152" width="38" height="28"/><rect class="fig-box-blue" x="350" y="152" width="38" height="28"/><rect class="fig-box-blue" x="388" y="152" width="38" height="28"/>
    <rect class="fig-box" x="452" y="54" width="214" height="130" rx="6"/>
    <text class="fig-title" x="230" y="36" text-anchor="middle" font-size="12.5">KMP 滑动对齐：S =“abababaa”, T =“ababaa”</text>
    <text class="fig-muted" x="141" y="49" text-anchor="middle" font-size="10">1</text><text class="fig-muted" x="179" y="49" text-anchor="middle" font-size="10">2</text><text class="fig-muted" x="217" y="49" text-anchor="middle" font-size="10">3</text><text class="fig-muted" x="255" y="49" text-anchor="middle" font-size="10">4</text><text class="fig-muted" x="293" y="49" text-anchor="middle" font-size="10">5</text><text class="fig-accent" x="331" y="49" text-anchor="middle" font-size="10.5">i=6</text><text class="fig-muted" x="369" y="49" text-anchor="middle" font-size="10">7</text><text class="fig-muted" x="407" y="49" text-anchor="middle" font-size="10">8</text>
    <text class="fig-label" x="72" y="72" text-anchor="middle" font-size="11.5">主串 S</text>
    <text class="fig-label" x="141" y="72" text-anchor="middle" font-size="12">a</text><text class="fig-label" x="179" y="72" text-anchor="middle" font-size="12">b</text><text class="fig-green" x="217" y="72" text-anchor="middle" font-size="12">a</text><text class="fig-green" x="255" y="72" text-anchor="middle" font-size="12">b</text><text class="fig-green" x="293" y="72" text-anchor="middle" font-size="12">a</text><text class="fig-accent" x="331" y="72" text-anchor="middle" font-size="12">b</text><text class="fig-label" x="369" y="72" text-anchor="middle" font-size="12">a</text><text class="fig-label" x="407" y="72" text-anchor="middle" font-size="12">a</text>
    <text class="fig-muted" x="72" y="114" text-anchor="middle" font-size="11">失配态</text>
    <text class="fig-blue" x="141" y="114" text-anchor="middle" font-size="11.5">a</text><text class="fig-blue" x="179" y="114" text-anchor="middle" font-size="11.5">b</text><text class="fig-green" x="217" y="114" text-anchor="middle" font-size="11.5">a</text><text class="fig-green" x="255" y="114" text-anchor="middle" font-size="11.5">b</text><text class="fig-green" x="293" y="114" text-anchor="middle" font-size="11.5">a</text><text class="fig-red" x="331" y="114" text-anchor="middle" font-size="11.5">a✗</text>
    <text class="fig-red" x="392" y="114" text-anchor="middle" font-size="10.5">j=6 失配</text>
    <text class="fig-orange" x="116" y="142" text-anchor="end" font-size="10.5">右滑 k−next[k] 位</text>
    <text class="fig-green" x="72" y="170" text-anchor="middle" font-size="11">对齐态</text>
    <text class="fig-green" x="217" y="170" text-anchor="middle" font-size="11.5">a</text><text class="fig-green" x="255" y="170" text-anchor="middle" font-size="11.5">b</text><text class="fig-green" x="293" y="170" text-anchor="middle" font-size="11.5">a</text><text class="fig-accent" x="331" y="170" text-anchor="middle" font-size="11.5">b✓</text><text class="fig-blue" x="369" y="170" text-anchor="middle" font-size="11.5">a✓</text><text class="fig-blue" x="407" y="170" text-anchor="middle" font-size="11.5">a✓</text>
    <text class="fig-accent" x="331" y="212" text-anchor="middle" font-size="11">i = 6 原地不动，T[next[6]] = T[4] 直接对准 S[6]，前 3 位“aba”免重比！</text>
    <text class="fig-accent" x="559" y="76" text-anchor="middle" font-size="11.5">已匹配串 T[1..5] =“ababa”</text>
    <text class="fig-green" x="559" y="96" text-anchor="middle" font-size="11">真前缀“aba”= 真后缀“aba”</text>
    <text class="fig-label" x="559" y="116" text-anchor="middle" font-size="11">最长相等长度 r = 3</text>
    <text class="fig-orange" x="559" y="136" text-anchor="middle" font-size="11.5">next[6] = r + 1 = 4</text>
    <text class="fig-muted" x="559" y="156" text-anchor="middle" font-size="10.5">右移步数 = j − next[j] = 2</text>
    <text class="fig-muted" x="559" y="173" text-anchor="middle" font-size="10.5">总时间 O(n + m)，支持流式处理</text>
  </svg>
  <figcaption>KMP 无回溯匹配示意：利用 T[1..5] 的最长相等真前后缀“aba”（r=3），将 T[4] 直接滑至 S[6] 继续比较</figcaption>
</figure>

**复杂度**：求 $next$ 为 $O(m)$，匹配为 $O(n)$，总计 $O(n+m)$。因 $i$ 只进不退，可一遍扫描完成，适合边读入边匹配（流式处理）。

### next 与 nextval 的手算

**求 next 的步骤**：

1. $next[1]=0$，$next[2]=1$（前 1 个字符没有真前后缀）；
2. 对 $j\ge 3$：在 $T[1..j-1]$ 中找**最长的相等真前缀与真后缀**，长度记为 $r$，则 $next[j]=r+1$；找不到取 1。

“真”指不含 $T[1..j-1]$ 整体自身。逐位比较时可从 $r=1$ 递增试，取满足条件的最大值。

**例 1**：模式串 `T = abaabcac`

| $j$ | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| $T[j]$ | a | b | a | a | b | c | a | c |
| 最长相等真前后缀长度 $r$ | — | 0 | 0 | 1 | 1 | 2 | 0 | 1 |
| $next[j]$ | 0 | 1 | 1 | 2 | 2 | 3 | 1 | 2 |
| $nextval[j]$ | 0 | 1 | 0 | 2 | 1 | 3 | 0 | 2 |

核对几项：$j=4$ 时 $T[1..3]$ 为 `aba`，前缀 `a` = 后缀 `a`，$r=1$，故 $next[4]=2$；$j=6$ 时 $T[1..5]$ 为 `abaab`，`ab`=`ab` 且更长的 `aba`≠`aab`，$r=2$，故 $next[6]=3$；$j=7$ 时 `abaabc` 无相等真前后缀，取 1。

**nextval 的修正规则**：先求出 next，再逐位修正：

- $nextval[1]=0$；
- 若 $T[j]=T[next[j]]$，则 $nextval[j]=nextval[next[j]]$；
- 否则 $nextval[j]=next[j]$。

理由：回退后的字符若与失配字符相同，回退后必然再次失配，可直接沿链继续前跳，一步到位。

上表核对：$j=3$ 时 $next[3]=1$、$T[3]$ 与 $T[1]$ 同为 `a`，故 $nextval[3]=nextval[1]=0$；$j=5$ 时 $next[5]=2$、$T[5]$ 与 $T[2]$ 同为 `b`，故 $nextval[5]=nextval[2]=1$；$j=8$ 时 $next[8]=2$，但 $T[8]$ 为 `c`、$T[2]$ 为 `b`，故 $nextval[8]=2$。

**例 2**：模式串 `T = aaaaab`

| $j$ | 1 | 2 | 3 | 4 | 5 | 6 |
| --- | --- | --- | --- | --- | --- | --- |
| $T[j]$ | a | a | a | a | a | b |
| $next[j]$ | 0 | 1 | 2 | 3 | 4 | 5 |
| $nextval[j]$ | 0 | 0 | 0 | 0 | 0 | 5 |

用 next 时，若在第 5 位失配，$j$ 会依次退到 4、3、2、1 逐个试，全是无效比较；用 nextval 直接 $j=0$，$i$ 前移一位，避免连锁回退。

> **★考点**：手算 next 只做一件事——在**前 $j-1$ 个字符**里找最长的相等真前缀与真后缀；nextval 是在 next 上做“同字符则继承”的修正。

> **注意**：以上公式以“下标从 1 开始、模式串存于 `T[1..m]`”为前提。若用 0 下标数组 `T[0..m-1]`，next 各值整体减 1（$next[0]=-1$），匹配代码中判据相应改为 `j == -1`。

<figure class="cpd-figure not-content" id="wz-w2-fig-12">
  <svg viewBox="0 0 700 256" role="img" aria-label="模式串 T=abaabcac 的 next 最长相等真前后缀手算原理与 nextval 同字符跳越修正">
    <defs>
      <marker id="wz-w2-arr-12" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="18" y="16" width="664" height="224" rx="8"/>
    <path class="fig-line" stroke="var(--sl-color-green)" stroke-width="1.5" d="M 176 52 Q 248 34 320 52"/>
    <path class="fig-line" stroke="var(--sl-color-orange)" stroke-width="1.5" d="M 248 166 Q 204 196 158 166" marker-end="url(#wz-w2-arr-12)"/>
    <path class="fig-line" stroke="var(--sl-color-purple)" stroke-width="1.5" d="M 338 166 Q 272 204 202 166" marker-end="url(#wz-w2-arr-12)"/>
    <rect class="fig-box" x="42" y="64" width="90" height="24"/><rect class="fig-box" x="42" y="88" width="90" height="26"/><rect class="fig-box" x="42" y="114" width="90" height="26"/><rect class="fig-box" x="42" y="140" width="90" height="26"/>
    <rect class="fig-box" x="132" y="64" width="45" height="24"/><rect class="fig-box" x="177" y="64" width="45" height="24"/><rect class="fig-box" x="222" y="64" width="45" height="24"/><rect class="fig-box" x="267" y="64" width="45" height="24"/><rect class="fig-box" x="312" y="64" width="45" height="24"/><rect class="fig-box-accent" x="357" y="64" width="45" height="24"/><rect class="fig-box" x="402" y="64" width="45" height="24"/><rect class="fig-box" x="447" y="64" width="45" height="24"/>
    <rect class="fig-box-green" x="132" y="88" width="45" height="26"/><rect class="fig-box-green" x="177" y="88" width="45" height="26"/><rect class="fig-box-blue" x="222" y="88" width="45" height="26"/><rect class="fig-box-green" x="267" y="88" width="45" height="26"/><rect class="fig-box-green" x="312" y="88" width="45" height="26"/><rect class="fig-box-accent" x="357" y="88" width="45" height="26"/><rect class="fig-box-blue" x="402" y="88" width="45" height="26"/><rect class="fig-box-blue" x="447" y="88" width="45" height="26"/>
    <rect class="fig-box" x="132" y="114" width="45" height="26"/><rect class="fig-box" x="177" y="114" width="45" height="26"/><rect class="fig-box-orange" x="222" y="114" width="45" height="26"/><rect class="fig-box" x="267" y="114" width="45" height="26"/><rect class="fig-box-purple" x="312" y="114" width="45" height="26"/><rect class="fig-box-accent" x="357" y="114" width="45" height="26"/><rect class="fig-box" x="402" y="114" width="45" height="26"/><rect class="fig-box" x="447" y="114" width="45" height="26"/>
    <rect class="fig-box" x="132" y="140" width="45" height="26"/><rect class="fig-box" x="177" y="140" width="45" height="26"/><rect class="fig-box-orange" x="222" y="140" width="45" height="26"/><rect class="fig-box" x="267" y="140" width="45" height="26"/><rect class="fig-box-purple" x="312" y="140" width="45" height="26"/><rect class="fig-box-accent" x="357" y="140" width="45" height="26"/><rect class="fig-box-orange" x="402" y="140" width="45" height="26"/><rect class="fig-box" x="447" y="140" width="45" height="26"/>
    <rect class="fig-box" x="506" y="64" width="162" height="156" rx="6"/>
    <text class="fig-title" x="266" y="34" text-anchor="middle" font-size="12">手算示范：T =“abaabcac”（绿色为 j=6 前子串的最长相等真前后缀“ab”）</text>
    <text class="fig-label" x="87" y="80" text-anchor="middle" font-size="11">位序 j</text>
    <text class="fig-label" x="87" y="105" text-anchor="middle" font-size="11">模式串 T[j]</text>
    <text class="fig-label" x="87" y="131" text-anchor="middle" font-size="11">next[j]</text>
    <text class="fig-label" x="87" y="157" text-anchor="middle" font-size="11">nextval[j]</text>
    <text class="fig-muted" x="154" y="80" text-anchor="middle" font-size="11">1</text><text class="fig-muted" x="199" y="80" text-anchor="middle" font-size="11">2</text><text class="fig-muted" x="244" y="80" text-anchor="middle" font-size="11">3</text><text class="fig-muted" x="289" y="80" text-anchor="middle" font-size="11">4</text><text class="fig-muted" x="334" y="80" text-anchor="middle" font-size="11">5</text><text class="fig-accent" x="379" y="80" text-anchor="middle" font-size="11">6</text><text class="fig-muted" x="424" y="80" text-anchor="middle" font-size="11">7</text><text class="fig-muted" x="469" y="80" text-anchor="middle" font-size="11">8</text>
    <text class="fig-green" x="154" y="106" text-anchor="middle" font-size="12">a</text><text class="fig-green" x="199" y="106" text-anchor="middle" font-size="12">b</text><text class="fig-blue" x="244" y="106" text-anchor="middle" font-size="12">a</text><text class="fig-green" x="289" y="106" text-anchor="middle" font-size="12">a</text><text class="fig-green" x="334" y="106" text-anchor="middle" font-size="12">b</text><text class="fig-accent" x="379" y="106" text-anchor="middle" font-size="12">c</text><text class="fig-blue" x="424" y="106" text-anchor="middle" font-size="12">a</text><text class="fig-blue" x="469" y="106" text-anchor="middle" font-size="12">c</text>
    <text class="fig-label" x="154" y="131" text-anchor="middle" font-size="11.5">0</text><text class="fig-label" x="199" y="131" text-anchor="middle" font-size="11.5">1</text><text class="fig-orange" x="244" y="131" text-anchor="middle" font-size="11.5">1</text><text class="fig-label" x="289" y="131" text-anchor="middle" font-size="11.5">2</text><text class="fig-purple" x="334" y="131" text-anchor="middle" font-size="11.5">2</text><text class="fig-accent" x="379" y="131" text-anchor="middle" font-size="11.5">3</text><text class="fig-label" x="424" y="131" text-anchor="middle" font-size="11.5">1</text><text class="fig-label" x="469" y="131" text-anchor="middle" font-size="11.5">2</text>
    <text class="fig-label" x="154" y="157" text-anchor="middle" font-size="11.5">0</text><text class="fig-label" x="199" y="157" text-anchor="middle" font-size="11.5">1</text><text class="fig-orange" x="244" y="157" text-anchor="middle" font-size="11.5">0</text><text class="fig-label" x="289" y="157" text-anchor="middle" font-size="11.5">2</text><text class="fig-purple" x="334" y="157" text-anchor="middle" font-size="11.5">1</text><text class="fig-accent" x="379" y="157" text-anchor="middle" font-size="11.5">3</text><text class="fig-orange" x="424" y="157" text-anchor="middle" font-size="11.5">0</text><text class="fig-label" x="469" y="157" text-anchor="middle" font-size="11.5">2</text>
    <text class="fig-orange" x="172" y="216" font-size="10.5">j=3: T[3]==T[1]==‘a’ → 继承 nextval[1]=0</text>
    <text class="fig-purple" x="172" y="231" font-size="10.5">j=5: T[5]==T[2]==‘b’ → 继承 nextval[2]=1</text>
    <text class="fig-title" x="587" y="84" text-anchor="middle" font-size="11.5">两步秒杀口诀</text>
    <text class="fig-green" x="587" y="106" text-anchor="middle" font-size="10.5">① 求 next[j]：看前 j−1 位</text>
    <text class="fig-muted" x="587" y="122" text-anchor="middle" font-size="10">r=2（“ab”=“ab”）→ 2+1=3</text>
    <text class="fig-orange" x="587" y="146" text-anchor="middle" font-size="10.5">② 求 nextval[j]：比字符</text>
    <text class="fig-muted" x="587" y="162" text-anchor="middle" font-size="10">若 T[j] == T[next[j]]</text>
    <text class="fig-orange" x="587" y="178" text-anchor="middle" font-size="10">抄 nextval[next[j]]</text>
    <text class="fig-muted" x="587" y="196" text-anchor="middle" font-size="10">若不同（如 j=6: c≠a）</text>
    <text class="fig-accent" x="587" y="211" text-anchor="middle" font-size="10">直接保留原 next[j]=3</text>
  </svg>
  <figcaption>next 与 nextval 手算对照：先由 T[1..j−1] 真前后缀求 next，再按“字符相同则往前继承”一步消除无效连锁回退</figcaption>
</figure>

> **交互演示**：[KMP 与朴素模式匹配及 next/nextval 推导](/lab/chapter-4/#lab-kmp)

### 模式匹配的应用：环状病毒 DNA 检测

病毒 DNA 是**环状**序列，长度 $m$，转动后仍是同一种病毒。例如 `baa` 的等价形式有 `baa`、`aab`、`aba` 共 $m$ 种循环移位。判断患者 DNA（主串 $S$）是否被感染，就是判断某个循环移位是否在 $S$ 中出现。

做法：把模式串 $T$ 复制一遍接在其后，得到长度 $2m$ 的串；令 $k=0,1,\dots,m-1$，依次取 $T[k+1..k+m]$（长度 $m$）与 $S$ 做一次模式匹配；任一次成功即感染，$m$ 次全部失败则未感染。

- `T = baa`，`S1 = aaabbba` 含 `aab` → 感染；`S2 = babbba` 不含 `baa`/`aab`/`aba` → 未感染。
- 复杂度：$m$ 次匹配，每次 $O(n+m)$，总计 $O\big(m(n+m)\big)$。用 BF 或 KMP 均可，KMP 每次匹配更快。

<figure class="cpd-figure not-content" id="wz-w2-fig-13">
  <svg viewBox="0 0 700 228" role="img" aria-label="环状病毒 DNA 模式串 T=baa 倍增为 baabaa 取滑动窗口与患者 DNA 主串匹配过程">
    <defs>
      <marker id="wz-w2-arr-13" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="18" y="16" width="664" height="196" rx="8"/>
    <circle class="fig-line-dashed" cx="84" cy="114" r="42"/>
    <line class="fig-line" stroke="var(--sl-color-gray-4)" stroke-width="1.4" x1="138" y1="114" x2="174" y2="114" marker-end="url(#wz-w2-arr-13)"/>
    <line class="fig-line" stroke="var(--sl-color-green)" stroke-width="1.5" x1="382" y1="128" x2="432" y2="128" marker-end="url(#wz-w2-arr-13)"/>
    <circle class="fig-box-accent" cx="84" cy="72" r="16"/>
    <circle class="fig-box-blue" cx="48" cy="135" r="16"/>
    <circle class="fig-box-blue" cx="120" cy="135" r="16"/>
    <rect class="fig-box-blue" x="182" y="54" width="32" height="26"/><rect class="fig-box-blue" x="214" y="54" width="32" height="26"/><rect class="fig-box-blue" x="246" y="54" width="32" height="26"/><rect class="fig-box-purple" x="278" y="54" width="32" height="26"/><rect class="fig-box-purple" x="310" y="54" width="32" height="26"/><rect class="fig-box-purple" x="342" y="54" width="32" height="26"/>
    <rect class="fig-box" x="182" y="90" width="96" height="22" rx="3"/>
    <rect class="fig-box-green" x="214" y="116" width="96" height="24" rx="3"/>
    <rect class="fig-box" x="246" y="144" width="96" height="22" rx="3"/>
    <rect class="fig-box" x="438" y="88" width="32" height="28"/><rect class="fig-box-green" x="470" y="88" width="32" height="28"/><rect class="fig-box-green" x="502" y="88" width="32" height="28"/><rect class="fig-box-green" x="534" y="88" width="32" height="28"/><rect class="fig-box" x="566" y="88" width="32" height="28"/><rect class="fig-box" x="598" y="88" width="32" height="28"/><rect class="fig-box" x="630" y="88" width="32" height="28"/>
    <rect class="fig-box-green" x="438" y="132" width="224" height="58" rx="5"/>
    <text class="fig-title" x="84" y="38" text-anchor="middle" font-size="12">环状病毒 T</text>
    <text class="fig-accent" x="84" y="76" text-anchor="middle" font-size="12">b</text>
    <text class="fig-blue" x="48" y="139" text-anchor="middle" font-size="12">a</text>
    <text class="fig-blue" x="120" y="139" text-anchor="middle" font-size="12">a</text>
    <text class="fig-muted" x="84" y="182" text-anchor="middle" font-size="10.5">m = 3 种旋转态</text>
    <text class="fig-title" x="278" y="38" text-anchor="middle" font-size="12">倍增拼接 T + T（长 2m = 6）</text>
    <text class="fig-blue" x="198" y="71" text-anchor="middle" font-size="11.5">b</text><text class="fig-blue" x="230" y="71" text-anchor="middle" font-size="11.5">a</text><text class="fig-blue" x="262" y="71" text-anchor="middle" font-size="11.5">a</text><text class="fig-purple" x="294" y="71" text-anchor="middle" font-size="11.5">b</text><text class="fig-purple" x="326" y="71" text-anchor="middle" font-size="11.5">a</text><text class="fig-purple" x="358" y="71" text-anchor="middle" font-size="11.5">a</text>
    <text class="fig-muted" x="230" y="105" text-anchor="middle" font-size="10.5">k=0: “baa”</text>
    <text class="fig-green" x="262" y="132" text-anchor="middle" font-size="11">k=1: “aab” ✓</text>
    <text class="fig-muted" x="294" y="159" text-anchor="middle" font-size="10.5">k=2: “aba”</text>
    <text class="fig-muted" x="278" y="186" text-anchor="middle" font-size="10.5">长 m 滑窗枚举全部循环移位</text>
    <text class="fig-title" x="550" y="38" text-anchor="middle" font-size="12">患者 DNA 主串 S₁ =“aaabbba”</text>
    <text class="fig-muted" x="550" y="76" text-anchor="middle" font-size="10.5">在位置 2..4 命中循环变体“aab”</text>
    <text class="fig-label" x="454" y="106" text-anchor="middle" font-size="11.5">a</text><text class="fig-green" x="486" y="106" text-anchor="middle" font-size="11.5">a</text><text class="fig-green" x="518" y="106" text-anchor="middle" font-size="11.5">a</text><text class="fig-green" x="550" y="106" text-anchor="middle" font-size="11.5">b</text><text class="fig-label" x="582" y="106" text-anchor="middle" font-size="11.5">b</text><text class="fig-label" x="614" y="106" text-anchor="middle" font-size="11.5">b</text><text class="fig-label" x="646" y="106" text-anchor="middle" font-size="11.5">a</text>
    <text class="fig-green" x="550" y="154" text-anchor="middle" font-size="11.5">任一滑窗匹配成功 → 判定感染！</text>
    <text class="fig-muted" x="550" y="174" text-anchor="middle" font-size="10.5">至多 m 趟 KMP，总时间 O(m(n + m))</text>
  </svg>
  <figcaption>环状串匹配技巧：将长度 m 的环状模式串首尾相接复制为 2m 线性串，用滑动窗口转化为 m 次常规模式匹配</figcaption>
</figure>

### 数组的定义与特点

**数组**：按一定格式排列起来的、具有**相同类型**的数据元素的集合。

- 一维数组排成一行（或一列），就是**定长线性表**，逻辑结构为线性结构。
- 二维数组：每个元素本身又是一个定长线性表。按行看是 $m$ 个行向量，按列看是 $n$ 个列向量。
- 元素 $a_{ij}$ 在行方向有前驱和后继，在列方向也有前驱和后继，**不再是一对一关系**，因此二维及以上的数组是线性结构的推广，本质属非线性结构（课程称“特殊的线性结构”）。
- 递推定义：$n-1$ 维数组的每个元素又是一个一维数组，即为 $n$ 维数组；线性表是一维数组的特例。

定义示例：`int a[5];` 元素为 `a[0]`–`a[4]`；`int nm[5][8];` 第一维长 5（行号 0–4），第二维长 8（列号 0–7），共 $5\times 8=40$ 个元素。

**特点与操作**：维数、各维上下界、元素个数一经定义便固定，元素类型相同且等长。因结构固定，插入/删除会破坏其形态，故数组只做初始化、销毁、取元素、修改元素值。

### 数组的顺序存储与地址计算

数组几乎总用顺序存储：结构固定、不做插删，链式结构没有优势。内存单元地址是一维线性的，多维数组必须约定映射次序：

- **行优先（行序为主序）**：一行存完再存下一行，C/Java 采用；
- **列优先（列序为主序）**：一列存完再存下一列，Fortran 采用。

设每个元素占 $L$ 个存储单元，$LOC$ 表示首地址。

一维数组（0 下标）：
$$
LOC(a_i)=LOC(a_0)+i\cdot L
$$

二维数组 $m$ 行 $n$ 列，**行优先、0 下标**：
$$
LOC(a_{ij})=LOC(a_{00})+(i\cdot n+j)\,L
$$

**行优先、1 下标**（$a[1..m][1..n]$）：
$$
LOC(a_{ij})=LOC(a_{11})+\big[(i-1)\,n+(j-1)\big]L
$$

**列优先、0 下标**：
$$
LOC(a_{ij})=LOC(a_{00})+(j\cdot m+i)\,L
$$

$n$ 维数组（0 下标，各维长度为 $b_1,\dots,b_n$）：
$$
LOC(j_1,j_2,\dots,j_n)=LOC(0,\dots,0)+\Big(\sum_{k=1}^{n} j_k\prod_{l=k+1}^{n} b_l\Big)L
$$

> **★考点**：公式不必死记。本质是“**该元素前面有多少个元素 × L + 首地址**”。行优先时先数满整行（$i\cdot n$ 个），再加本行前面 $j$ 个。

**例**：$a[m][n]$ 按行优先存储，$a[0][0]$ 在 644，$a[2][2]$ 在 676，每元素占 1 个单元。
$$
(2n+2)\times 1=676-644=32\ \Rightarrow\ n=15
$$
$$
LOC(a_{33})=644+(3\times 15+3)\times 1=644+48=692
$$

<figure class="cpd-figure not-content" id="wz-w2-fig-14">
  <svg viewBox="0 0 700 256" role="img" aria-label="二维数组 3×4 按行优先与按列优先映射到一维连续内存及偏移地址计算">
    <defs>
      <marker id="wz-w2-arr-14" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="18" y="16" width="214" height="224" rx="8"/>
    <rect class="fig-box-subtle" x="246" y="16" width="436" height="224" rx="8"/>
    <path class="fig-line" stroke="var(--sl-color-accent)" stroke-width="1.5" d="M 113 138 L 113 160 L 238 160 L 238 82 L 484 82 L 484 68" marker-end="url(#wz-w2-arr-14)"/>
    <rect class="fig-box-blue" x="48" y="58" width="38" height="28"/><rect class="fig-box-blue" x="86" y="58" width="38" height="28"/><rect class="fig-box-blue" x="124" y="58" width="38" height="28"/><rect class="fig-box-blue" x="162" y="58" width="38" height="28"/>
    <rect class="fig-box-green" x="48" y="86" width="38" height="28"/><rect class="fig-box-green" x="86" y="86" width="38" height="28"/><rect class="fig-box-green" x="124" y="86" width="38" height="28"/><rect class="fig-box-green" x="162" y="86" width="38" height="28"/>
    <rect class="fig-box-orange" x="48" y="114" width="38" height="28"/><rect class="fig-box-accent" x="86" y="114" width="38" height="28"/><rect class="fig-box" x="124" y="114" width="38" height="28"/><rect class="fig-box" x="162" y="114" width="38" height="28"/>
    <rect class="fig-box-blue" x="262" y="42" width="124" height="24" rx="3"/>
    <rect class="fig-box-green" x="386" y="42" width="124" height="24" rx="3"/>
    <rect class="fig-box-orange" x="510" y="42" width="32" height="24" rx="3"/>
    <rect class="fig-box-accent" x="542" y="42" width="36" height="24" rx="3"/>
    <rect class="fig-box" x="578" y="42" width="86" height="24" rx="3"/>
    <rect class="fig-box-purple" x="262" y="128" width="96" height="24" rx="3"/>
    <rect class="fig-box-purple" x="358" y="128" width="64" height="24" rx="3"/>
    <rect class="fig-box-accent" x="422" y="128" width="42" height="24" rx="3"/>
    <rect class="fig-box" x="464" y="128" width="200" height="24" rx="3"/>
    <rect class="fig-box" x="262" y="172" width="402" height="54" rx="5"/>
    <text class="fig-title" x="125" y="36" text-anchor="middle" font-size="12">二维数组 A[3][4]（0 下标）</text>
    <text class="fig-blue" x="67" y="76" text-anchor="middle" font-size="10.5">a₀₀</text><text class="fig-blue" x="105" y="76" text-anchor="middle" font-size="10.5">a₀₁</text><text class="fig-blue" x="143" y="76" text-anchor="middle" font-size="10.5">a₀₂</text><text class="fig-blue" x="181" y="76" text-anchor="middle" font-size="10.5">a₀₃</text>
    <text class="fig-green" x="67" y="104" text-anchor="middle" font-size="10.5">a₁₀</text><text class="fig-green" x="105" y="104" text-anchor="middle" font-size="10.5">a₁₁</text><text class="fig-green" x="143" y="104" text-anchor="middle" font-size="10.5">a₁₂</text><text class="fig-green" x="181" y="104" text-anchor="middle" font-size="10.5">a₁₃</text>
    <text class="fig-orange" x="67" y="132" text-anchor="middle" font-size="10.5">a₂₀</text><text class="fig-accent" x="105" y="132" text-anchor="middle" font-size="10.5">a₂₁</text><text class="fig-muted" x="143" y="132" text-anchor="middle" font-size="10.5">a₂₂</text><text class="fig-muted" x="181" y="132" text-anchor="middle" font-size="10.5">a₂₃</text>
    <text class="fig-muted" x="125" y="184" text-anchor="middle" font-size="10.5">m = 3 行，n = 4 列</text>
    <text class="fig-accent" x="125" y="202" text-anchor="middle" font-size="10.5">目标：求 a₂₁（i=2, j=1）</text>
    <text class="fig-muted" x="125" y="220" text-anchor="middle" font-size="10">1下标版把 i,j 换成 i−1,j−1</text>
    <text class="fig-title" x="262" y="34" font-size="11.5">① 行优先（C / Java）：前 i=2 整行（2×4=8）+ 本行前 j=1 个 = 9</text>
    <text class="fig-blue" x="324" y="58" text-anchor="middle" font-size="10.5">第0行 4个</text>
    <text class="fig-green" x="448" y="58" text-anchor="middle" font-size="10.5">第1行 4个</text>
    <text class="fig-orange" x="526" y="58" text-anchor="middle" font-size="10">a₂₀</text>
    <text class="fig-accent" x="560" y="58" text-anchor="middle" font-size="10.5">a₂₁</text>
    <text class="fig-muted" x="621" y="58" text-anchor="middle" font-size="10">a₂₂, a₂₃</text>
    <text class="fig-accent" x="464" y="98" text-anchor="middle" font-size="11">LOC(aᵢⱼ) = LOC(a₀₀) + (i · n + j) × L = LOC + 9L</text>
    <text class="fig-title" x="262" y="120" font-size="11.5">② 列优先（Fortran）：前 j=1 整列（1×3=3）+ 本列前 i=2 个 = 5</text>
    <text class="fig-purple" x="310" y="144" text-anchor="middle" font-size="10.5">第0列 3个</text>
    <text class="fig-purple" x="390" y="144" text-anchor="middle" font-size="10">a₀₁,a₁₁</text>
    <text class="fig-accent" x="443" y="144" text-anchor="middle" font-size="10.5">a₂₁</text>
    <text class="fig-muted" x="564" y="144" text-anchor="middle" font-size="10">第2列(3个)、第3列(3个)</text>
    <text class="fig-purple" x="464" y="166" text-anchor="middle" font-size="11">LOC(aᵢⱼ) = LOC(a₀₀) + (j · m + i) × L = LOC + 5L</text>
    <text class="fig-label" x="463" y="192" text-anchor="middle" font-size="11">万能定址本质：地址 = 基址 +（排在它前面的元素总数）× L</text>
    <text class="fig-muted" x="463" y="212" text-anchor="middle" font-size="10.5">408 读题先盯紧三要素：① 行优先还是列优先 · ② 下标从 0 还是 1 起 · ③ 元素字节 L</text>
  </svg>
  <figcaption>二维数组一维线性化定址：行优先数满整行 i·n 加列偏移 j，列优先数满整列 j·m 加行偏移 i</figcaption>
</figure>

### 对称矩阵的压缩存储

**压缩存储**：多个值相同的元素只分配一个存储单元；零元素不分配存储单元。

**对称矩阵**满足 $a_{ij}=a_{ji}$（$n\times n$，沿主对角线对称）。只需存**下三角**（含对角线），元素个数为
$$
1+2+\cdots+n=\frac{n(n+1)}{2}
$$
用一维数组 `sa[0 .. n(n+1)/2 - 1]` 按行序存放。

**映射公式**（$i,j$ 从 1 起，$k$ 从 0 起）：

| 情况 | $k$ |
| --- | --- |
| $i\ge j$ | $\dfrac{i(i-1)}{2}+j-1$ |
| $i<j$ | $\dfrac{j(j-1)}{2}+i-1$ |

推导：$a_{ij}$ 之前有完整的 $i-1$ 行，共 $1+2+\cdots+(i-1)=\frac{i(i-1)}{2}$ 个元素；本行前面还有 $j-1$ 个。$i<j$ 时利用对称性取 $a_{ji}$，即交换 $i,j$。

**0 下标形式**（$i,j,k$ 均从 0 起）：$i\ge j$ 时 $k=\frac{i(i+1)}{2}+j$；$i<j$ 时 $k=\frac{j(j+1)}{2}+i$。

例：$n=5$ 时原需 25 个单元，压缩后只需 $\frac{5\times 6}{2}=15$ 个。

<figure class="cpd-figure not-content" id="wz-fig-10">
  <svg viewBox="0 0 700 296" role="img" aria-label="4×4 对称矩阵下三角压缩存储到一维数组 sa[0..9] 的无交叉映射">
    <defs>
      <marker id="wz-arr-10" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="18" y="12" width="664" height="272" rx="8"/>
    <path class="fig-line" stroke="var(--sl-color-accent)" stroke-width="1.6" d="M 95 146 L 95 154 L 218 154 L 218 206 L 415 206 L 415 228" marker-end="url(#wz-arr-10)"/>
    <rect class="fig-box-blue" x="30" y="48" width="42" height="30"/><rect class="fig-box-dashed" x="74" y="48" width="42" height="30"/><rect class="fig-box-dashed" x="118" y="48" width="42" height="30"/><rect class="fig-box-dashed" x="162" y="48" width="42" height="30"/>
    <rect class="fig-box-blue" x="30" y="82" width="42" height="30"/><rect class="fig-box-blue" x="74" y="82" width="42" height="30"/><rect class="fig-box-orange" x="118" y="82" width="42" height="30"/><rect class="fig-box-dashed" x="162" y="82" width="42" height="30"/>
    <rect class="fig-box-blue" x="30" y="116" width="42" height="30"/><rect class="fig-box-accent" x="74" y="116" width="42" height="30"/><rect class="fig-box-blue" x="118" y="116" width="42" height="30"/><rect class="fig-box-dashed" x="162" y="116" width="42" height="30"/>
    <rect class="fig-box-blue" x="30" y="162" width="42" height="30"/><rect class="fig-box-blue" x="74" y="162" width="42" height="30"/><rect class="fig-box-blue" x="118" y="162" width="42" height="30"/><rect class="fig-box-blue" x="162" y="162" width="42" height="30"/>
    <rect class="fig-box" x="236" y="48" width="430" height="98" rx="6"/>
    <rect class="fig-box-blue" x="226" y="232" width="42" height="28"/><rect class="fig-box-blue" x="268" y="232" width="42" height="28"/><rect class="fig-box-blue" x="310" y="232" width="42" height="28"/><rect class="fig-box-blue" x="352" y="232" width="42" height="28"/><rect class="fig-box-accent" x="394" y="232" width="42" height="28"/><rect class="fig-box-blue" x="436" y="232" width="42" height="28"/><rect class="fig-box-blue" x="478" y="232" width="42" height="28"/><rect class="fig-box-blue" x="520" y="232" width="42" height="28"/><rect class="fig-box-blue" x="562" y="232" width="42" height="28"/><rect class="fig-box-blue" x="604" y="232" width="42" height="28"/>
    <text class="fig-title" x="30" y="34" font-size="12.5">4×4 对称矩阵只存下三角：n(n + 1) / 2 = 10 个元素</text>
    <text class="fig-blue" x="51" y="67" text-anchor="middle" font-size="11">a₁₁</text><text class="fig-muted" x="95" y="67" text-anchor="middle" font-size="11">a₁₂</text><text class="fig-muted" x="139" y="67" text-anchor="middle" font-size="11">a₁₃</text><text class="fig-muted" x="183" y="67" text-anchor="middle" font-size="11">a₁₄</text>
    <text class="fig-blue" x="51" y="101" text-anchor="middle" font-size="11">a₂₁</text><text class="fig-blue" x="95" y="101" text-anchor="middle" font-size="11">a₂₂</text><text class="fig-orange" x="139" y="101" text-anchor="middle" font-size="11">a₂₃</text><text class="fig-muted" x="183" y="101" text-anchor="middle" font-size="11">a₂₄</text>
    <text class="fig-blue" x="51" y="135" text-anchor="middle" font-size="11">a₃₁</text><text class="fig-accent" x="95" y="135" text-anchor="middle" font-size="11">a₃₂</text><text class="fig-blue" x="139" y="135" text-anchor="middle" font-size="11">a₃₃</text><text class="fig-muted" x="183" y="135" text-anchor="middle" font-size="11">a₃₄</text>
    <text class="fig-blue" x="51" y="181" text-anchor="middle" font-size="11">a₄₁</text><text class="fig-blue" x="95" y="181" text-anchor="middle" font-size="11">a₄₂</text><text class="fig-blue" x="139" y="181" text-anchor="middle" font-size="11">a₄₃</text><text class="fig-blue" x="183" y="181" text-anchor="middle" font-size="11">a₄₄</text>
    <text class="fig-accent" x="252" y="70" font-size="12">定位示例：a₃₂（第 3 行第 2 列，i = 3, j = 2，i ≥ j）</text>
    <text class="fig-label" x="252" y="92" font-size="11.5">前 2 行共 1 + 2 = 3 个，本行前有 1 个 → k = 3×2/2 + 2 − 1 = 4（sa[4]）</text>
    <text class="fig-orange" x="252" y="114" font-size="11.5">若查上三角对称元 a₂₃（i &lt; j）：互换行列号取 a₃₂，同样落入 sa[4]</text>
    <text class="fig-muted" x="252" y="134" font-size="10.5">0 下标版（i,j,k 均从 0 起）：i ≥ j 时 k = i(i + 1)/2 + j</text>
    <text class="fig-label" x="226" y="222" font-size="11.5">一维压缩数组 sa[0..9]</text>
    <text class="fig-blue" x="247" y="250" text-anchor="middle" font-size="11">a₁₁</text><text class="fig-blue" x="289" y="250" text-anchor="middle" font-size="11">a₂₁</text><text class="fig-blue" x="331" y="250" text-anchor="middle" font-size="11">a₂₂</text><text class="fig-blue" x="373" y="250" text-anchor="middle" font-size="11">a₃₁</text><text class="fig-accent" x="415" y="250" text-anchor="middle" font-size="11">a₃₂</text><text class="fig-blue" x="457" y="250" text-anchor="middle" font-size="11">a₃₃</text><text class="fig-blue" x="499" y="250" text-anchor="middle" font-size="11">a₄₁</text><text class="fig-blue" x="541" y="250" text-anchor="middle" font-size="11">a₄₂</text><text class="fig-blue" x="583" y="250" text-anchor="middle" font-size="11">a₄₃</text><text class="fig-blue" x="625" y="250" text-anchor="middle" font-size="11">a₄₄</text>
    <text class="fig-muted" x="247" y="274" text-anchor="middle" font-size="10">0</text><text class="fig-muted" x="289" y="274" text-anchor="middle" font-size="10">1</text><text class="fig-muted" x="331" y="274" text-anchor="middle" font-size="10">2</text><text class="fig-muted" x="373" y="274" text-anchor="middle" font-size="10">3</text><text class="fig-accent" x="415" y="274" text-anchor="middle" font-size="10.5">4</text><text class="fig-muted" x="457" y="274" text-anchor="middle" font-size="10">5</text><text class="fig-muted" x="499" y="274" text-anchor="middle" font-size="10">6</text><text class="fig-muted" x="541" y="274" text-anchor="middle" font-size="10">7</text><text class="fig-muted" x="583" y="274" text-anchor="middle" font-size="10">8</text><text class="fig-muted" x="625" y="274" text-anchor="middle" font-size="10">9</text>
  </svg>
  <figcaption>对称矩阵压缩存储：仅存下三角 n(n+1)/2 个元素，上三角 a₂₃ 借对称性共享 a₃₂ 在 sa[4] 的单元</figcaption>
</figure>

### 三角矩阵与对角矩阵的压缩存储

**三角矩阵**：下三角矩阵的对角线以上（不含对角线）元素全为同一常数 $c$；上三角矩阵的对角线以下元素全为 $c$。

存储方式：三角区的 $\frac{n(n+1)}{2}$ 个元素按行序存入一维数组，常数 $c$ 只占 1 个单元，故数组大小为
$$
\frac{n(n+1)}{2}+1
$$
（比对称矩阵多一个单元）。下三角取法与对称矩阵完全相同，只是 $i<j$ 时返回 $c$ 的下标 $\frac{n(n+1)}{2}$。

**上三角**（只存 $i\le j$，按行序，$i,j$ 从 1 起，$k$ 从 0 起）：
$$
k=\frac{(i-1)(2n-i+2)}{2}+(j-i)
$$

推导：前 $i-1$ 行元素个数为 $n+(n-1)+\cdots+(n-i+2)=\frac{(i-1)(2n-i+2)}{2}$；本行前面有 $j-i$ 个。校验：$i=1,j=1\Rightarrow k=0$；$i=1,j=n\Rightarrow k=n-1$；$i=2,j=2\Rightarrow k=n$。$i>j$ 时（下三角的常数区）取 $c$ 的下标 $\frac{n(n+1)}{2}$。

**对角矩阵（带状矩阵）**：非零元集中在主对角线两侧的带状区域，其余全为 0。含 $k$ 条非零对角线的称 $k$ 对角矩阵：三对角（$|i-j|\le 1$）3 条，五对角 5 条，依此类推。

- 三对角矩阵共 $3n-2$ 个非零元。按行优先压缩，$i,j$ 从 1 起、$k$ 从 0 起：
$$
k=2i+j-3
$$
校验：$a_{11}\to 0$，$a_{12}\to 1$，$a_{21}\to 2$（第 2 行从下标 2 开始），$a_{nn}\to 2n+n-3=3n-3$，正是最后一个下标。
- 课程中的五对角例子采用**按对角线逐条存储**：以主对角线为第 0 行，上偏一条为 $-1$ 行、下偏一条为 $+1$ 行……$6\times 6$ 五对角矩阵用 $5\times 6=30$ 个单元（每行按列数补齐）。这种方式实现简单，但定位单个元素需先算对角线与列偏移。

> **★考点**：三角矩阵压缩后大小是 $\frac{n(n+1)}{2}+1$（含常数 $c$），对称矩阵是 $\frac{n(n+1)}{2}$；$n$ 越大、带宽越窄，压缩收益越明显。

<figure class="cpd-figure not-content" id="wz-w2-fig-15">
  <svg viewBox="0 0 700 264" role="img" aria-label="4×4 上三角矩阵含常数区压缩存储与三对角带状矩阵按行压缩存储对比">
    <defs>
      <marker id="wz-w2-arr-15" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="18" y="16" width="328" height="232" rx="8"/>
    <rect class="fig-box-subtle" x="358" y="16" width="324" height="232" rx="8"/>
    <path class="fig-line" stroke="var(--sl-color-orange)" stroke-width="1.5" d="M 52 162 L 52 174 L 306 174 L 306 184" marker-end="url(#wz-w2-arr-15)"/>
    <rect class="fig-box-blue" x="34" y="46" width="34" height="26"/><rect class="fig-box-blue" x="68" y="46" width="34" height="26"/><rect class="fig-box-blue" x="102" y="46" width="34" height="26"/><rect class="fig-box-blue" x="136" y="46" width="34" height="26"/>
    <rect class="fig-box-orange" x="34" y="74" width="34" height="26"/><rect class="fig-box-blue" x="68" y="74" width="34" height="26"/><rect class="fig-box-blue" x="102" y="74" width="34" height="26"/><rect class="fig-box-blue" x="136" y="74" width="34" height="26"/>
    <rect class="fig-box-orange" x="34" y="102" width="34" height="26"/><rect class="fig-box-orange" x="68" y="102" width="34" height="26"/><rect class="fig-box-blue" x="102" y="102" width="34" height="26"/><rect class="fig-box-blue" x="136" y="102" width="34" height="26"/>
    <rect class="fig-box-orange" x="34" y="130" width="34" height="26"/><rect class="fig-box-orange" x="68" y="130" width="34" height="26"/><rect class="fig-box-orange" x="102" y="130" width="34" height="26"/><rect class="fig-box-blue" x="136" y="130" width="34" height="26"/>
    <rect class="fig-box" x="182" y="46" width="152" height="110" rx="5"/>
    <rect class="fig-box-blue" x="34" y="188" width="252" height="26" rx="3"/>
    <rect class="fig-box-orange" x="288" y="188" width="42" height="26" rx="3"/>
    <rect class="fig-box-green" x="374" y="46" width="34" height="26"/><rect class="fig-box-green" x="408" y="46" width="34" height="26"/><rect class="fig-box-dashed" x="442" y="46" width="34" height="26"/><rect class="fig-box-dashed" x="476" y="46" width="34" height="26"/>
    <rect class="fig-box-green" x="374" y="74" width="34" height="26"/><rect class="fig-box-green" x="408" y="74" width="34" height="26"/><rect class="fig-box-green" x="442" y="74" width="34" height="26"/><rect class="fig-box-dashed" x="476" y="74" width="34" height="26"/>
    <rect class="fig-box-dashed" x="374" y="102" width="34" height="26"/><rect class="fig-box-accent" x="408" y="102" width="34" height="26"/><rect class="fig-box-green" x="442" y="102" width="34" height="26"/><rect class="fig-box-green" x="476" y="102" width="34" height="26"/>
    <rect class="fig-box-dashed" x="374" y="130" width="34" height="26"/><rect class="fig-box-dashed" x="408" y="130" width="34" height="26"/><rect class="fig-box-green" x="442" y="130" width="34" height="26"/><rect class="fig-box-green" x="476" y="130" width="34" height="26"/>
    <rect class="fig-box" x="522" y="46" width="146" height="110" rx="5"/>
    <rect class="fig-box-green" x="374" y="188" width="294" height="26" rx="3"/>
    <text class="fig-title" x="182" y="34" text-anchor="middle" font-size="12">① 上三角矩阵：n(n + 1)/2 + 1 = 11 格</text>
    <text class="fig-blue" x="51" y="63" text-anchor="middle" font-size="10">a₁₁</text><text class="fig-blue" x="85" y="63" text-anchor="middle" font-size="10">a₁₂</text><text class="fig-blue" x="119" y="63" text-anchor="middle" font-size="10">a₁₃</text><text class="fig-blue" x="153" y="63" text-anchor="middle" font-size="10">a₁₄</text>
    <text class="fig-orange" x="51" y="91" text-anchor="middle" font-size="10.5">c</text><text class="fig-blue" x="85" y="91" text-anchor="middle" font-size="10">a₂₂</text><text class="fig-blue" x="119" y="91" text-anchor="middle" font-size="10">a₂₃</text><text class="fig-blue" x="153" y="91" text-anchor="middle" font-size="10">a₂₄</text>
    <text class="fig-orange" x="51" y="119" text-anchor="middle" font-size="10.5">c</text><text class="fig-orange" x="85" y="119" text-anchor="middle" font-size="10.5">c</text><text class="fig-blue" x="119" y="119" text-anchor="middle" font-size="10">a₃₃</text><text class="fig-blue" x="153" y="119" text-anchor="middle" font-size="10">a₃₄</text>
    <text class="fig-orange" x="51" y="147" text-anchor="middle" font-size="10.5">c</text><text class="fig-orange" x="85" y="147" text-anchor="middle" font-size="10.5">c</text><text class="fig-orange" x="119" y="147" text-anchor="middle" font-size="10.5">c</text><text class="fig-blue" x="153" y="147" text-anchor="middle" font-size="10">a₄₄</text>
    <text class="fig-blue" x="258" y="68" text-anchor="middle" font-size="10.5">上三角区 (i ≤ j)：</text>
    <text class="fig-label" x="258" y="86" text-anchor="middle" font-size="10">k=(i−1)(2n−i+2)/2+j−i</text>
    <text class="fig-orange" x="258" y="112" text-anchor="middle" font-size="10.5">常数区 (i &gt; j)：</text>
    <text class="fig-orange" x="258" y="128" text-anchor="middle" font-size="10.5">全部共享末尾单元</text>
    <text class="fig-muted" x="258" y="144" text-anchor="middle" font-size="10">k = n(n+1)/2 = 10</text>
    <text class="fig-blue" x="160" y="205" text-anchor="middle" font-size="10.5">sa[0..9]：a₁₁ a₁₂ a₁₃ a₁₄ a₂₂ … a₄₄</text>
    <text class="fig-orange" x="309" y="205" text-anchor="middle" font-size="10.5">sa[10]:c</text>
    <text class="fig-muted" x="182" y="232" text-anchor="middle" font-size="10.5">★ 易错：若下三角为常数 c（非全不存），必加 1 格！</text>
    <text class="fig-title" x="520" y="34" text-anchor="middle" font-size="12">② 三对角带状矩阵：3n − 2 = 10 格</text>
    <text class="fig-green" x="391" y="63" text-anchor="middle" font-size="10">a₁₁</text><text class="fig-green" x="425" y="63" text-anchor="middle" font-size="10">a₁₂</text><text class="fig-muted" x="459" y="63" text-anchor="middle" font-size="10">0</text><text class="fig-muted" x="493" y="63" text-anchor="middle" font-size="10">0</text>
    <text class="fig-green" x="391" y="91" text-anchor="middle" font-size="10">a₂₁</text><text class="fig-green" x="425" y="91" text-anchor="middle" font-size="10">a₂₂</text><text class="fig-green" x="459" y="91" text-anchor="middle" font-size="10">a₂₃</text><text class="fig-muted" x="493" y="91" text-anchor="middle" font-size="10">0</text>
    <text class="fig-muted" x="391" y="119" text-anchor="middle" font-size="10">0</text><text class="fig-accent" x="425" y="119" text-anchor="middle" font-size="10">a₃₂</text><text class="fig-green" x="459" y="119" text-anchor="middle" font-size="10">a₃₃</text><text class="fig-green" x="493" y="119" text-anchor="middle" font-size="10">a₃₄</text>
    <text class="fig-muted" x="391" y="147" text-anchor="middle" font-size="10">0</text><text class="fig-muted" x="425" y="147" text-anchor="middle" font-size="10">0</text><text class="fig-green" x="459" y="147" text-anchor="middle" font-size="10">a₄₃</text><text class="fig-green" x="493" y="147" text-anchor="middle" font-size="10">a₄₄</text>
    <text class="fig-green" x="595" y="68" text-anchor="middle" font-size="10.5">带状条件 |i − j| ≤ 1</text>
    <text class="fig-label" x="595" y="88" text-anchor="middle" font-size="10.5">首尾行各 2 个，中间 3 个</text>
    <text class="fig-accent" x="595" y="110" text-anchor="middle" font-size="11">k = 2i + j − 3（0 起）</text>
    <text class="fig-muted" x="595" y="128" text-anchor="middle" font-size="10">如 a₃₂：2×3+2−3 = 5</text>
    <text class="fig-muted" x="595" y="144" text-anchor="middle" font-size="10">反求：i=⌊(k+1)/3⌋+1</text>
    <text class="fig-green" x="521" y="205" text-anchor="middle" font-size="9.2">sa[0..9]：a₁₁ a₁₂ | a₂₁ a₂₂ a₂₃ | a₃₂ a₃₃ a₃₄ | a₄₃ a₄₄</text>
    <text class="fig-muted" x="520" y="232" text-anchor="middle" font-size="10.5">零元素规定不占存储单元，总长 2 + 3(n − 2) + 2 = 3n − 2</text>
  </svg>
  <figcaption>上三角矩阵与三对角矩阵压缩对比：三角矩阵末尾多留 1 格存常数 c，三对角矩阵仅存带状非零元</figcaption>
</figure>

### 稀疏矩阵的三元组与十字链表

**稀疏矩阵**：$m\times n$ 矩阵中非零元只有 $t$ 个，稀疏因子
$$
\delta=\frac{t}{m\times n}\le 0.05
$$
即非零元不超过 5%，其余 95% 以上是零。

**三元组表示**：每个非零元记为 $(i,\ j,\ a_{ij})$，即行号、列号、值。三元组顺序表：

```c
#define MAXSIZE 12500
typedef struct {
    int i, j;
    ElemType e;
} Triple;
typedef struct {
    Triple data[MAXSIZE + 1];   /* data[0] 依次存总行数、总列数、非零元个数 */
    int mu, nu, tu;             /* 总行数、总列数、非零元个数 */
} TSMatrix;
```

课程实现中直接把三个统计量以三元组形式存入 0 号单元。

三元组按**行序、行内按列序**排列（有序的双下标法）；三个统计量必须一并保存，读取时才能还原矩阵形状。

- 优点：空间只与非零元个数有关；按行序处理方便。
- 缺点：**不能随机存取**——查某个非零元必须从头扫描；运算后若零变非零或非零变零，插入/删除要大量移动元素。

<figure class="cpd-figure not-content" id="wz-w2-fig-16">
  <svg viewBox="0 0 700 264" role="img" aria-label="稀疏矩阵三元组顺序表 TSMatrix 与快速转置辅助数组 num、cpot 定位机制">
    <defs>
      <marker id="wz-w2-arr-16" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="18" y="16" width="664" height="232" rx="8"/>
    <path class="fig-line" stroke="var(--sl-color-green)" stroke-width="1.5" d="M 326 122 L 516 98" marker-end="url(#wz-w2-arr-16)"/>
    <path class="fig-line" stroke="var(--sl-color-orange)" stroke-width="1.5" d="M 326 170 L 516 146" marker-end="url(#wz-w2-arr-16)"/>
    <rect class="fig-box" x="32" y="54" width="128" height="128" rx="4"/>
    <rect class="fig-box-purple" x="184" y="60" width="142" height="24"/>
    <rect class="fig-box-blue" x="184" y="84" width="142" height="24"/>
    <rect class="fig-box-green" x="184" y="108" width="142" height="24"/>
    <rect class="fig-box-blue" x="184" y="132" width="142" height="24"/>
    <rect class="fig-box-orange" x="184" y="156" width="142" height="24"/>
    <rect class="fig-box" x="348" y="64" width="148" height="114" rx="5"/>
    <rect class="fig-box-purple" x="520" y="60" width="144" height="24"/>
    <rect class="fig-box-green" x="520" y="84" width="144" height="24"/>
    <rect class="fig-box-blue" x="520" y="108" width="144" height="24"/>
    <rect class="fig-box-orange" x="520" y="132" width="144" height="24"/>
    <rect class="fig-box-blue" x="520" y="156" width="144" height="24"/>
    <rect class="fig-box" x="32" y="196" width="632" height="38" rx="5"/>
    <text class="fig-title" x="96" y="38" text-anchor="middle" font-size="12">原矩阵 M（3×4, tu=4）</text>
    <text class="fig-blue" x="96" y="80" text-anchor="middle" font-size="11.5">0    12    9    0</text>
    <text class="fig-green" x="96" y="118" text-anchor="middle" font-size="11.5">−3    0    0    0</text>
    <text class="fig-orange" x="96" y="156" text-anchor="middle" font-size="11.5">0    −7    0    5</text>
    <text class="fig-title" x="255" y="38" text-anchor="middle" font-size="12">M.data[0..4]（按行序）</text>
    <text class="fig-purple" x="255" y="76" text-anchor="middle" font-size="10.5">[0] (3, 4, 4) 表头统计</text>
    <text class="fig-blue" x="255" y="100" text-anchor="middle" font-size="10.5">[1] (1, 2, 12)</text>
    <text class="fig-green" x="255" y="124" text-anchor="middle" font-size="10.5">[2] (1, 3, 9) → 跳写</text>
    <text class="fig-blue" x="255" y="148" text-anchor="middle" font-size="10.5">[3] (2, 1, −3)</text>
    <text class="fig-orange" x="255" y="172" text-anchor="middle" font-size="10.5">[4] (3, 2, −7) → 跳写</text>
    <text class="fig-title" x="422" y="38" text-anchor="middle" font-size="12">快速转置辅助向量</text>
    <text class="fig-label" x="422" y="84" text-anchor="middle" font-size="10.5">列号 col： 1   2   3   4</text>
    <text class="fig-blue" x="422" y="108" text-anchor="middle" font-size="10.5">num[col]：1   2   1   0</text>
    <text class="fig-accent" x="422" y="132" text-anchor="middle" font-size="10.5">cpot[col]：1   2   4   5</text>
    <text class="fig-muted" x="422" y="156" text-anchor="middle" font-size="9.5">cpot[c]=cpot[c−1]+num[c−1]</text>
    <text class="fig-muted" x="422" y="171" text-anchor="middle" font-size="9.5">每填一个元素 cpot[c]++</text>
    <text class="fig-title" x="592" y="38" text-anchor="middle" font-size="12">转置 T.data（一步到位）</text>
    <text class="fig-purple" x="592" y="76" text-anchor="middle" font-size="10.5">[0] (4, 3, 4) 行列互换</text>
    <text class="fig-green" x="592" y="100" text-anchor="middle" font-size="10.5">[1] (1, 2, −3) cpot[1]</text>
    <text class="fig-blue" x="592" y="124" text-anchor="middle" font-size="10.5">[2] (2, 1, 12) cpot[2]</text>
    <text class="fig-orange" x="592" y="148" text-anchor="middle" font-size="10.5">[3] (2, 3, −7) cpot[2]+1</text>
    <text class="fig-blue" x="592" y="172" text-anchor="middle" font-size="10.5">[4] (3, 1, 9)  cpot[3]</text>
    <text class="fig-label" x="350" y="213" text-anchor="middle" font-size="11">普通转置按列反复扫描需 O(nu · tu)；快速转置先算每列非零元个数 num 与首位置 cpot，单趟归位仅需 O(nu + tu)</text>
    <text class="fig-muted" x="350" y="228" text-anchor="middle" font-size="10">注意：三元组转置绝不能只交换每个结点的 (i, j)，必须重排为按新行号（原列号）递增有序！</text>
  </svg>
  <figcaption>稀疏矩阵三元组顺序表与快速转置：借助 num[] 与 cpot[] 预知每列起始槽位，实现 O(nu + tu) 一次就位</figcaption>
</figure>

**十字链表**适合非零元动态变化的场合（矩阵加法、乘法）：

```c
typedef struct OLNode {
    int i, j;
    ElemType e;
    struct OLNode *right, *down;
} OLNode, *OLink;
```

每个非零元一个结点，共 5 个域：

- `i`、`j`：行号、列号；`e`：元素值；
- `right`：指向**同一行**的下一个非零元；
- `down`：指向**同一列**的下一个非零元。

另设行头指针数组 `rhead[1..m]` 与列头指针数组 `chead[1..n]`，分别指向各行、各列的第一个非零元；某行/列无非零元则对应指针为空。行链与列链在结点处交叉成十字，故名十字链表。

> **注意**：稀疏矩阵的“稀疏”由 $\delta\le 0.05$ 判定，没有非零元绝对个数标准；三元组宜静态、少变动，十字链表宜频繁插删。

<figure class="cpd-figure not-content" id="wz-w2-fig-17">
  <svg viewBox="0 0 700 264" role="img" aria-label="稀疏矩阵十字链表存储结构：rhead 行头数组、chead 列头数组与五域交叉结点">
    <defs>
      <marker id="wz-w2-arr-17" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="18" y="16" width="444" height="232" rx="8"/>
    <rect class="fig-box-subtle" x="476" y="16" width="206" height="232" rx="8"/>
    <line class="fig-line" stroke="var(--sl-color-blue)" stroke-width="1.4" x1="88" y1="112" x2="210" y2="112" marker-end="url(#wz-w2-arr-17)"/>
    <line class="fig-line" stroke="var(--sl-color-blue)" stroke-width="1.4" x1="286" y1="112" x2="314" y2="112" marker-end="url(#wz-w2-arr-17)"/>
    <line class="fig-line" stroke="var(--sl-color-blue)" stroke-width="1.4" x1="88" y1="162" x2="114" y2="162" marker-end="url(#wz-w2-arr-17)"/>
    <line class="fig-line" stroke="var(--sl-color-blue)" stroke-width="1.4" x1="88" y1="212" x2="210" y2="212" marker-end="url(#wz-w2-arr-17)"/>
    <line class="fig-line" stroke="var(--sl-color-green)" stroke-width="1.4" x1="150" y1="74" x2="150" y2="144" marker-end="url(#wz-w2-arr-17)"/>
    <line class="fig-line" stroke="var(--sl-color-green)" stroke-width="1.4" x1="250" y1="74" x2="250" y2="94" marker-end="url(#wz-w2-arr-17)"/>
    <line class="fig-line" stroke="var(--sl-color-green)" stroke-width="1.4" x1="250" y1="130" x2="250" y2="194" marker-end="url(#wz-w2-arr-17)"/>
    <line class="fig-line" stroke="var(--sl-color-green)" stroke-width="1.4" x1="354" y1="74" x2="354" y2="94" marker-end="url(#wz-w2-arr-17)"/>
    <rect class="fig-box-purple" x="34" y="98" width="54" height="28" rx="3"/>
    <rect class="fig-box-purple" x="34" y="148" width="54" height="28" rx="3"/>
    <rect class="fig-box-purple" x="34" y="198" width="54" height="28" rx="3"/>
    <rect class="fig-box-orange" x="118" y="46" width="64" height="28" rx="3"/>
    <rect class="fig-box-orange" x="218" y="46" width="64" height="28" rx="3"/>
    <rect class="fig-box-orange" x="322" y="46" width="64" height="28" rx="3"/>
    <rect class="fig-box-dashed" x="396" y="46" width="52" height="28" rx="3"/>
    <rect class="fig-box-blue" x="214" y="98" width="72" height="32" rx="4"/>
    <rect class="fig-box-blue" x="318" y="98" width="72" height="32" rx="4"/>
    <rect class="fig-box-green" x="118" y="148" width="72" height="32" rx="4"/>
    <rect class="fig-box-accent" x="214" y="198" width="72" height="32" rx="4"/>
    <rect class="fig-box-blue" x="502" y="60" width="50" height="30"/><rect class="fig-box-blue" x="552" y="60" width="50" height="30"/><rect class="fig-box-accent" x="602" y="60" width="54" height="30"/>
    <rect class="fig-box-green" x="502" y="90" width="77" height="30"/><rect class="fig-box-purple" x="579" y="90" width="77" height="30"/>
    <rect class="fig-box" x="492" y="138" width="174" height="96" rx="5"/>
    <text class="fig-title" x="240" y="34" text-anchor="middle" font-size="12">十字链表（Orthogonal List）行链与列链正交编织</text>
    <text class="fig-purple" x="61" y="116" text-anchor="middle" font-size="10">rhead[1]</text>
    <text class="fig-purple" x="61" y="166" text-anchor="middle" font-size="10">rhead[2]</text>
    <text class="fig-purple" x="61" y="216" text-anchor="middle" font-size="10">rhead[3]</text>
    <text class="fig-orange" x="150" y="64" text-anchor="middle" font-size="10">chead[1]</text>
    <text class="fig-orange" x="250" y="64" text-anchor="middle" font-size="10">chead[2]</text>
    <text class="fig-orange" x="354" y="64" text-anchor="middle" font-size="10">chead[3]</text>
    <text class="fig-muted" x="422" y="64" text-anchor="middle" font-size="9.5">c[4]=∧</text>
    <text class="fig-blue" x="250" y="118" text-anchor="middle" font-size="10.5">1 | 2 | 12</text>
    <text class="fig-blue" x="354" y="118" text-anchor="middle" font-size="10.5">1 | 3 | 9 ∧</text>
    <text class="fig-green" x="154" y="168" text-anchor="middle" font-size="10.5">2 | 1 | −3 ∧</text>
    <text class="fig-accent" x="250" y="218" text-anchor="middle" font-size="10.5">3 | 2 | −7 ∧</text>
    <text class="fig-title" x="579" y="38" text-anchor="middle" font-size="12">OLNode 五域结点结构</text>
    <text class="fig-blue" x="527" y="79" text-anchor="middle" font-size="11">i 行</text>
    <text class="fig-blue" x="577" y="79" text-anchor="middle" font-size="11">j 列</text>
    <text class="fig-accent" x="629" y="79" text-anchor="middle" font-size="11">e 值</text>
    <text class="fig-green" x="540" y="109" text-anchor="middle" font-size="10.5">down 列链</text>
    <text class="fig-purple" x="617" y="109" text-anchor="middle" font-size="10.5">right 行链</text>
    <text class="fig-label" x="579" y="158" text-anchor="middle" font-size="10.5">适用场景：A + B 或 A × B</text>
    <text class="fig-muted" x="579" y="176" text-anchor="middle" font-size="10">相加抵消变 0 → 直接摘除结点</text>
    <text class="fig-muted" x="579" y="194" text-anchor="middle" font-size="10">0 变非 0 → 行链+列链双向插入</text>
    <text class="fig-green" x="579" y="214" text-anchor="middle" font-size="10.5">彻底免去三元组整表搬移！</text>
  </svg>
  <figcaption>稀疏矩阵十字链表：每个非零元同时挂入第 i 行链表（right）与第 j 列链表（down），支持动态插删</figcaption>
</figure>

> **交互演示**：[特殊矩阵压缩与稀疏矩阵转置](/lab/chapter-5/#lab-matrix_symmetric)

### 广义表的定义、表头与表尾

**广义表**是线性表的推广：
$$
LS=(a_1,a_2,\dots,a_n),\qquad n\ge 0
$$
每个 $a_i$ 或为**原子**（不可再分的单个元素，通常记小写字母），或为**子表**（本身又是一个广义表，通常记大写字母）。定义中出现自身，属**递归定义**。

- **表名** $LS$；**长度** = 元素个数 $n$；**深度** = 展开后括号的最大嵌套层数。
- `GetHead(LS)` 取**表头** = 第一个元素 $a_1$，可以是原子，也可以是子表。
- `GetTail(LS)` 取**表尾** = 除表头外其余元素构成的表 $(a_2,\dots,a_n)$，**一定是一个表，必须加括号**。

| 广义表 | 长度 | 深度 | 表头 `GetHead` | 表尾 `GetTail` |
| --- | --- | --- | --- | --- |
| $A=()$ | 0 | 1 | 无 | 无 |
| $B=(())$ | 1 | 2 | $()$ | $()$ |
| $C=(a,(b,c))$ | 2 | 2 | $a$ | $((b,c))$ |
| $D=(a,b,c)$ | 3 | 1 | $a$ | $(b,c)$ |
| $E=(C,D)$ | 2 | 3 | $C$ | $(D)$ |
| $F=(a,F)$ | 2 | $\infty$ | $a$ | $(F)$ |

要点辨析：

- $C$ 只有 2 个元素：原子 $a$ 与子表 $(b,c)$，不是 3 个。
- $D$ 的 3 个元素都是原子，故深度为 1；表尾是 $(b,c)$，不是 $c$。
- 表尾是“表”而不是“元素”：$D$ 的表尾写作 $(b,c)$（含两个元素的一个表）；若只写 `b,c`，就成了两个元素而非一个表。
- **原子深度为 0，空表深度为 1**（空表有一层括号）。$E$ 共享 $C,D$，深度 $=1+\max(2,1)=3$。

**性质**：

1. 元素有序，表头无前驱、表尾无后继（其余元素各有前驱和后继）；
2. 可被其他广义表**共享**（$E$ 共享 $C$、$D$；$B$ 共享空表）；
3. 可以是**递归表**（$F=(a,F)$），长度有限而深度无穷；
4. 是**多层次结构**，可用树形图表示：表为根，子表为子树，原子为叶结点；
5. 元素大小不一、且需区分原子与子表，**不能用数组存储**，通常用链式存储（结点设标志域区分原子结点与表结点）。

<figure class="cpd-figure not-content" id="wz-fig-11">
  <svg viewBox="0 0 700 246" role="img" aria-label="广义表 C=(a,(b,c)) 的树形层次表示与长度、深度、表头表尾拆解">
    <rect class="fig-box-subtle" x="18" y="14" width="388" height="218" rx="8"/>
    <rect class="fig-box-subtle" x="420" y="14" width="262" height="218" rx="8"/>
    <g class="fig-line">
      <line x1="212" y1="64" x2="118" y2="122"/>
      <line x1="212" y1="64" x2="300" y2="122"/>
      <line x1="300" y1="142" x2="252" y2="184"/>
      <line x1="300" y1="142" x2="348" y2="184"/>
    </g>
    <rect class="fig-box-accent" x="150" y="34" width="124" height="32" rx="6"/>
    <rect class="fig-box-green" x="72" y="114" width="92" height="32" rx="6"/>
    <rect class="fig-box-orange" x="242" y="114" width="116" height="32" rx="6"/>
    <rect class="fig-box-blue" x="220" y="178" width="64" height="30" rx="6"/>
    <rect class="fig-box-blue" x="316" y="178" width="64" height="30" rx="6"/>
    <rect class="fig-box-green" x="436" y="48" width="230" height="44" rx="5"/>
    <rect class="fig-box-orange" x="436" y="102" width="230" height="54" rx="5"/>
    <rect class="fig-box" x="436" y="166" width="230" height="52" rx="5"/>
    <text class="fig-accent" x="212" y="55" text-anchor="middle" font-size="12.5">表 C = (a, (b, c))</text>
    <text class="fig-green" x="118" y="135" text-anchor="middle" font-size="12">原子 a</text>
    <text class="fig-orange" x="300" y="135" text-anchor="middle" font-size="12">子表 (b, c)</text>
    <text class="fig-blue" x="252" y="198" text-anchor="middle" font-size="12">原子 b</text>
    <text class="fig-blue" x="348" y="198" text-anchor="middle" font-size="12">原子 c</text>
    <text class="fig-muted" x="42" y="54" font-size="10.5">第0层</text>
    <text class="fig-muted" x="42" y="134" font-size="10.5">第1层</text>
    <text class="fig-muted" x="42" y="198" font-size="10.5">第2层</text>
    <text class="fig-title" x="551" y="34" text-anchor="middle" font-size="12">GetHead / GetTail 易错对比</text>
    <text class="fig-green" x="551" y="67" text-anchor="middle" font-size="11.5">表头 GetHead(C) = a</text>
    <text class="fig-muted" x="551" y="84" text-anchor="middle" font-size="10.5">取第 1 个元素本身（可原子可子表）</text>
    <text class="fig-orange" x="551" y="121" text-anchor="middle" font-size="11.5">表尾 GetTail(C) = ((b, c))</text>
    <text class="fig-red" x="551" y="140" text-anchor="middle" font-size="10.5">★ 必套外层括号！绝不是 (b, c)！</text>
    <text class="fig-label" x="551" y="186" text-anchor="middle" font-size="11">长度 = 顶层分支数 = 2</text>
    <text class="fig-muted" x="551" y="206" text-anchor="middle" font-size="10.5">深度 = 括号最大层数 = 2（空表为 1）</text>
  </svg>
  <figcaption>广义表 C = (a, (b, c)) 的树形层次与表头表尾辨析：表头是首元素 a，表尾是剩余元素外加一层括号构成的 ((b, c))</figcaption>
</figure>

<figure class="cpd-figure not-content" id="wz-w2-fig-18">
  <svg viewBox="0 0 700 268" role="img" aria-label="广义表 C=(a,(b,c)) 的头尾链表存储结构与扩展线性链表存储结构对比">
    <defs>
      <marker id="wz-w2-arr-18" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="18" y="16" width="386" height="236" rx="8"/>
    <rect class="fig-box-subtle" x="418" y="16" width="264" height="236" rx="8"/>
    <line class="fig-line" stroke="var(--sl-color-accent)" stroke-width="1.5" x1="48" y1="74" x2="72" y2="74" marker-end="url(#wz-w2-arr-18)"/>
    <line class="fig-line" stroke="var(--sl-color-green)" stroke-width="1.4" x1="112" y1="88" x2="112" y2="122" marker-end="url(#wz-w2-arr-18)"/>
    <line class="fig-line" stroke="var(--sl-color-orange)" stroke-width="1.4" x1="148" y1="74" x2="196" y2="74" marker-end="url(#wz-w2-arr-18)"/>
    <line class="fig-line" stroke="var(--sl-color-blue)" stroke-width="1.4" x1="236" y1="88" x2="236" y2="132" marker-end="url(#wz-w2-arr-18)"/>
    <line class="fig-line" stroke="var(--sl-color-green)" stroke-width="1.4" x1="224" y1="160" x2="178" y2="194" marker-end="url(#wz-w2-arr-18)"/>
    <line class="fig-line" stroke="var(--sl-color-orange)" stroke-width="1.4" x1="260" y1="146" x2="300" y2="146" marker-end="url(#wz-w2-arr-18)"/>
    <line class="fig-line" stroke="var(--sl-color-green)" stroke-width="1.4" x1="338" y1="160" x2="338" y2="192" marker-end="url(#wz-w2-arr-18)"/>
    <line class="fig-line" stroke="var(--sl-color-accent)" stroke-width="1.4" x1="448" y1="78" x2="472" y2="78" marker-end="url(#wz-w2-arr-18)"/>
    <line class="fig-line" stroke="var(--sl-color-blue)" stroke-width="1.4" x1="504" y1="92" x2="504" y2="126" marker-end="url(#wz-w2-arr-18)"/>
    <line class="fig-line" stroke="var(--sl-color-orange)" stroke-width="1.4" x1="538" y1="140" x2="572" y2="140" marker-end="url(#wz-w2-arr-18)"/>
    <line class="fig-line" stroke="var(--sl-color-blue)" stroke-width="1.4" x1="604" y1="154" x2="604" y2="188" marker-end="url(#wz-w2-arr-18)"/>
    <rect class="fig-box-purple" x="76" y="60" width="22" height="28"/><rect class="fig-box-green" x="98" y="60" width="26" height="28"/><rect class="fig-box-orange" x="124" y="60" width="24" height="28"/>
    <rect class="fig-box-blue" x="86" y="126" width="24" height="28"/><rect class="fig-box-blue" x="110" y="126" width="30" height="28"/>
    <rect class="fig-box-purple" x="200" y="60" width="22" height="28"/><rect class="fig-box-blue" x="222" y="60" width="26" height="28"/><rect class="fig-box" x="248" y="60" width="24" height="28"/>
    <rect class="fig-box-purple" x="200" y="132" width="22" height="28"/><rect class="fig-box-green" x="222" y="132" width="24" height="28"/><rect class="fig-box-orange" x="246" y="132" width="24" height="28"/>
    <rect class="fig-box-blue" x="140" y="196" width="24" height="26"/><rect class="fig-box-blue" x="164" y="196" width="28" height="26"/>
    <rect class="fig-box-purple" x="304" y="132" width="22" height="28"/><rect class="fig-box-green" x="326" y="132" width="24" height="28"/><rect class="fig-box" x="350" y="132" width="24" height="28"/>
    <rect class="fig-box-blue" x="312" y="196" width="24" height="26"/><rect class="fig-box-blue" x="336" y="196" width="28" height="26"/>
    <rect class="fig-box-purple" x="476" y="64" width="20" height="26"/><rect class="fig-box-blue" x="496" y="64" width="22" height="26"/><rect class="fig-box" x="518" y="64" width="20" height="26"/>
    <rect class="fig-box-green" x="476" y="128" width="20" height="26"/><rect class="fig-box-green" x="496" y="128" width="22" height="26"/><rect class="fig-box-orange" x="518" y="128" width="20" height="26"/>
    <rect class="fig-box-purple" x="576" y="128" width="20" height="26"/><rect class="fig-box-blue" x="596" y="128" width="22" height="26"/><rect class="fig-box" x="618" y="128" width="20" height="26"/>
    <rect class="fig-box-green" x="562" y="190" width="46" height="26" rx="3"/>
    <rect class="fig-box-green" x="618" y="190" width="46" height="26" rx="3"/>
    <text class="fig-title" x="211" y="36" text-anchor="middle" font-size="12">① 头尾链表存储：C = (a, (b, c))</text>
    <text class="fig-accent" x="36" y="78" font-size="11.5">C</text>
    <text class="fig-purple" x="87" y="78" text-anchor="middle" font-size="10.5">1</text><text class="fig-green" x="111" y="78" text-anchor="middle" font-size="10">hp</text><text class="fig-orange" x="136" y="78" text-anchor="middle" font-size="10">tp</text>
    <text class="fig-blue" x="98" y="144" text-anchor="middle" font-size="10.5">0</text><text class="fig-blue" x="125" y="144" text-anchor="middle" font-size="11">a</text>
    <text class="fig-purple" x="211" y="78" text-anchor="middle" font-size="10.5">1</text><text class="fig-blue" x="235" y="78" text-anchor="middle" font-size="10">hp</text><text class="fig-muted" x="260" y="78" text-anchor="middle" font-size="10">∧</text>
    <text class="fig-orange" x="332" y="78" text-anchor="middle" font-size="10">← 表尾 ((b,c))</text>
    <text class="fig-purple" x="211" y="150" text-anchor="middle" font-size="10.5">1</text><text class="fig-green" x="234" y="150" text-anchor="middle" font-size="10">hp</text><text class="fig-orange" x="258" y="150" text-anchor="middle" font-size="10">tp</text>
    <text class="fig-blue" x="152" y="213" text-anchor="middle" font-size="10.5">0</text><text class="fig-blue" x="178" y="213" text-anchor="middle" font-size="11">b</text>
    <text class="fig-purple" x="315" y="150" text-anchor="middle" font-size="10.5">1</text><text class="fig-green" x="338" y="150" text-anchor="middle" font-size="10">hp</text><text class="fig-muted" x="362" y="150" text-anchor="middle" font-size="10">∧</text>
    <text class="fig-blue" x="324" y="213" text-anchor="middle" font-size="10.5">0</text><text class="fig-blue" x="350" y="213" text-anchor="middle" font-size="11">c</text>
    <text class="fig-muted" x="211" y="241" text-anchor="middle" font-size="10">tag=1 表结点 [1|hp|tp]（非空表至少 1 个）；tag=0 原子结点 [0|atom]</text>
    <text class="fig-title" x="550" y="36" text-anchor="middle" font-size="12">② 扩展线性链表（同构三域）</text>
    <text class="fig-accent" x="436" y="82" font-size="11.5">C</text>
    <text class="fig-purple" x="486" y="81" text-anchor="middle" font-size="10">1</text><text class="fig-blue" x="507" y="81" text-anchor="middle" font-size="9.5">hp</text><text class="fig-muted" x="528" y="81" text-anchor="middle" font-size="10">∧</text>
    <text class="fig-green" x="486" y="145" text-anchor="middle" font-size="10">0</text><text class="fig-green" x="507" y="145" text-anchor="middle" font-size="11">a</text><text class="fig-orange" x="528" y="145" text-anchor="middle" font-size="9.5">tp</text>
    <text class="fig-purple" x="586" y="145" text-anchor="middle" font-size="10">1</text><text class="fig-blue" x="607" y="145" text-anchor="middle" font-size="9.5">hp</text><text class="fig-muted" x="628" y="145" text-anchor="middle" font-size="10">∧</text>
    <text class="fig-green" x="585" y="207" text-anchor="middle" font-size="10">0|b|→</text>
    <text class="fig-green" x="641" y="207" text-anchor="middle" font-size="10">0|c|∧</text>
    <text class="fig-muted" x="550" y="241" text-anchor="middle" font-size="10">原子也带 tp 兄弟链，类比孩子兄弟树</text>
  </svg>
  <figcaption>广义表的两种链式存储：头尾链表中 tp 始终指向表尾（必为表结点或空），直观解释为何表尾永远是表</figcaption>
</figure>

线性表是广义表的特例：当所有元素都是同类型的原子时，广义表退化为线性表；推广后它可兼容线性表、数组乃至树、图等结构。

## 第5章 树和二叉树

### 树形结构与树的定义

线性结构中数据元素之间是**一对一**关系；树形结构是**一对多**（每个结点至多一个前驱，可有多个后继）；图形结构是**多对多**。树用来描述具有**层次关系**的数据，如家谱、组织机构、源程序语法结构、数据库索引、算法执行过程。

树的递归定义：

- 树是 $n\ (n \ge 0)$ 个结点的有限集合。
- $n=0$ 时称为**空树**。
- $n>0$ 时，有且仅有一个特定的结点称为**根**；其余结点可分为 $m\ (m \ge 0)$ 个**互不相交**的有限集合 $T_1,T_2,\dots,T_m$，每个集合本身又是一棵树，称为根的**子树**。

因为定义中“子树仍是一棵树”，树是**递归结构**，其上的操作通常也用递归实现。

常见表示方法：树形图（最常用）、嵌套集合、凹入表示（类似图书目录，缩进深度表示层次）、广义表。

<figure class="cpd-figure not-content" id="wz-w3-fig-1">
  <svg viewBox="0 0 700 228" role="img" aria-label="树的四种常见表示方法对比：树形图、文氏嵌套集合、凹入目录表示与广义表">
    <rect class="fig-box-subtle" x="16" y="14" width="166" height="200" rx="8"/>
    <rect class="fig-box-subtle" x="192" y="14" width="168" height="200" rx="8"/>
    <rect class="fig-box-subtle" x="370" y="14" width="154" height="200" rx="8"/>
    <rect class="fig-box-subtle" x="534" y="14" width="150" height="200" rx="8"/>
    <g class="fig-line">
      <line x1="99" y1="62" x2="52" y2="112"/>
      <line x1="99" y1="62" x2="99" y2="112"/>
      <line x1="99" y1="62" x2="146" y2="112"/>
      <line x1="52" y1="112" x2="36" y2="164"/>
      <line x1="52" y1="112" x2="72" y2="164"/>
      <line x1="146" y1="112" x2="146" y2="164"/>
    </g>
    <circle class="fig-box-accent" cx="99" cy="62" r="13"/>
    <circle class="fig-box-blue" cx="52" cy="112" r="13"/>
    <circle class="fig-box-green" cx="99" cy="112" r="13"/>
    <circle class="fig-box-blue" cx="146" cy="112" r="13"/>
    <g class="fig-box-green">
      <circle cx="36" cy="164" r="12"/>
      <circle cx="72" cy="164" r="12"/>
      <circle cx="146" cy="164" r="12"/>
    </g>
    <rect class="fig-box-accent" x="204" y="50" width="144" height="128" rx="18"/>
    <rect class="fig-box-blue" x="212" y="80" width="66" height="88" rx="12"/>
    <rect class="fig-box-green" x="220" y="106" width="22" height="24" rx="6"/>
    <rect class="fig-box-green" x="248" y="106" width="22" height="24" rx="6"/>
    <rect class="fig-box-green" x="284" y="84" width="24" height="32" rx="8"/>
    <rect class="fig-box-blue" x="314" y="80" width="28" height="88" rx="10"/>
    <rect class="fig-box-green" x="318" y="114" width="20" height="26" rx="6"/>
    <rect class="fig-box-accent" x="382" y="50" width="128" height="16" rx="3"/>
    <rect class="fig-box-blue" x="398" y="70" width="96" height="16" rx="3"/>
    <rect class="fig-box-green" x="414" y="90" width="56" height="15" rx="3"/>
    <rect class="fig-box-green" x="414" y="109" width="56" height="15" rx="3"/>
    <rect class="fig-box-green" x="398" y="128" width="76" height="16" rx="3"/>
    <rect class="fig-box-blue" x="398" y="148" width="96" height="16" rx="3"/>
    <rect class="fig-box-green" x="414" y="168" width="56" height="15" rx="3"/>
    <rect class="fig-box" x="546" y="56" width="126" height="62" rx="6"/>
    <rect class="fig-box" x="546" y="128" width="126" height="52" rx="6"/>
    <g font-size="12" text-anchor="middle">
      <text class="fig-title" x="99" y="34">① 树形图（最常用）</text>
      <text class="fig-title" x="276" y="34">② 嵌套集合（文氏图）</text>
      <text class="fig-title" x="447" y="34">③ 凹入表示（目录）</text>
      <text class="fig-title" x="609" y="34">④ 广义表表示</text>
      <text class="fig-accent" x="99" y="66">A</text>
      <text class="fig-blue" x="52" y="116">B</text>
      <text class="fig-green" x="99" y="116">C</text>
      <text class="fig-blue" x="146" y="116">D</text>
      <text class="fig-green" x="36" y="168" font-size="11">E</text>
      <text class="fig-green" x="72" y="168" font-size="11">F</text>
      <text class="fig-green" x="146" y="168" font-size="11">G</text>
      <text class="fig-accent" x="276" y="68">A</text>
      <text class="fig-blue" x="245" y="96" font-size="11">B</text>
      <text class="fig-green" x="231" y="122" font-size="10.5">E</text>
      <text class="fig-green" x="259" y="122" font-size="10.5">F</text>
      <text class="fig-green" x="296" y="104" font-size="11">C</text>
      <text class="fig-blue" x="328" y="96" font-size="11">D</text>
      <text class="fig-green" x="328" y="131" font-size="10.5">G</text>
    </g>
    <g font-size="10.5">
      <text class="fig-accent" x="388" y="62">A</text>
      <text class="fig-blue" x="404" y="82">B</text>
      <text class="fig-green" x="420" y="101">E</text>
      <text class="fig-green" x="420" y="120">F</text>
      <text class="fig-green" x="404" y="140">C</text>
      <text class="fig-blue" x="404" y="160">D</text>
      <text class="fig-green" x="420" y="179">G</text>
    </g>
    <g font-size="11" text-anchor="middle">
      <text class="fig-accent" x="609" y="77">T = A (</text>
      <text class="fig-blue" x="609" y="95">B(E, F), C, D(G)</text>
      <text class="fig-accent" x="609" y="112">)</text>
      <text class="fig-muted" x="609" y="148">括号深度 = 子树层数</text>
      <text class="fig-muted" x="609" y="168">原子结点 = 叶子</text>
      <text class="fig-muted" x="99" y="198">直观展现层次分支</text>
      <text class="fig-muted" x="276" y="198">子树集合互不相交</text>
      <text class="fig-muted" x="447" y="198">缩进量对应结点层数</text>
    </g>
  </svg>
  <figcaption>同一棵树 T 的四种等价表示：体现“根 + 互不相交子树集合”的递归本质</figcaption>
</figure>

### 树的基本术语

| 术语 | 含义 |
|---|---|
| 结点 | 数据元素 + 指向其子树的分支 |
| 根结点 | 树中唯一**没有前驱（无双亲）** 的结点 |
| 结点的度 | 该结点拥有的子树数，即后继数 / 分支数 |
| 树的度 | 树中所有结点度的**最大值** |
| 叶子（终端结点） | 度为 $0$ 的结点 |
| 分支结点（非终端结点） | 度不为 $0$ 的结点；除根外的分支结点称内部结点 |
| 双亲 / 孩子 | 子树根是该结点的孩子，该结点是子树根的双亲 |
| 兄弟 | 有**共同双亲**的结点 |
| 堂兄弟 | 双亲在同一层的结点（自身同层，双亲不同） |
| 祖先 | 从根到该结点路径上的所有结点 |
| 子孙 | 以某结点为根的子树中的所有结点 |
| 层次 | 根为第 1 层，其孩子为第 2 层，依此类推 |
| 深度 / 高度 | 树中结点的**最大层次** |
| 有序树 / 无序树 | 各结点的子树从左到右是否有次序；有序树交换子树即成为另一棵树 |
| 森林 | $m\ (m \ge 0)$ 棵互不相交的树的集合 |

森林与树的关系：删去树的根，其各棵子树构成森林；给森林中各树加上一个共同的双亲结点，森林变成一棵树；一棵树可看作只含一棵树的特殊森林。

<figure class="cpd-figure not-content" id="wz-fig-12">
  <svg viewBox="0 0 700 286" role="img" aria-label="树的基本术语示意：层次数、结点的度、叶子与分支结点、亲兄弟与堂兄弟、祖先与子孙">
    <defs>
      <marker id="wz-w3-arr-12" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="14" width="424" height="258" rx="8"/>
    <rect class="fig-box-subtle" x="452" y="14" width="232" height="258" rx="8"/>
    <g class="fig-line-dashed">
      <line x1="88" y1="54" x2="424" y2="54"/>
      <line x1="88" y1="126" x2="424" y2="126"/>
      <line x1="88" y1="202" x2="424" y2="202"/>
      <path d="M 122 222 Q 167 244 212 222"/>
      <path d="M 212 222 Q 279 252 346 222" stroke="var(--sl-color-purple)"/>
    </g>
    <g class="fig-line">
      <line x1="258" y1="54" x2="167" y2="126"/>
      <line x1="258" y1="54" x2="258" y2="126"/>
      <line x1="258" y1="54" x2="368" y2="126"/>
      <line x1="167" y1="126" x2="122" y2="202"/>
      <line x1="167" y1="126" x2="212" y2="202"/>
      <line x1="368" y1="126" x2="346" y2="202"/>
      <line x1="368" y1="126" x2="404" y2="202"/>
    </g>
    <circle class="fig-box-accent" cx="258" cy="54" r="17"/>
    <circle class="fig-box-blue" cx="167" cy="126" r="17"/>
    <circle class="fig-box-green" cx="258" cy="126" r="17"/>
    <circle class="fig-box-blue" cx="368" cy="126" r="17"/>
    <g class="fig-box-green">
      <circle cx="122" cy="202" r="17"/>
      <circle cx="212" cy="202" r="17"/>
      <circle cx="346" cy="202" r="17"/>
      <circle cx="404" cy="202" r="17"/>
    </g>
    <rect class="fig-box" x="135" y="232" width="64" height="18" rx="4"/>
    <rect class="fig-box-purple" x="242" y="236" width="74" height="18" rx="4"/>
    <rect class="fig-box" x="464" y="44" width="208" height="50" rx="6"/>
    <rect class="fig-box" x="464" y="102" width="208" height="50" rx="6"/>
    <rect class="fig-box" x="464" y="160" width="208" height="50" rx="6"/>
    <rect class="fig-box-orange" x="464" y="218" width="208" height="42" rx="6"/>
    <g font-size="13" text-anchor="middle">
      <text class="fig-accent" x="258" y="59">a</text>
      <text class="fig-blue" x="167" y="131">b</text>
      <text class="fig-green" x="258" y="131">c</text>
      <text class="fig-blue" x="368" y="131">d</text>
      <text class="fig-green" x="122" y="207">e</text>
      <text class="fig-green" x="212" y="207">f</text>
      <text class="fig-green" x="346" y="207">g</text>
      <text class="fig-green" x="404" y="207">h</text>
    </g>
    <g font-size="11.5">
      <text class="fig-title" x="30" y="32">层次</text>
      <text class="fig-muted" x="30" y="58">第 1 层</text>
      <text class="fig-muted" x="30" y="130">第 2 层</text>
      <text class="fig-muted" x="30" y="206">第 3 层</text>
      <text class="fig-accent" x="282" y="46" font-size="10.5">根（度=3）</text>
      <text class="fig-blue" x="120" y="118" font-size="10.5">度=2</text>
      <text class="fig-green" x="280" y="122" font-size="10.5">度=0</text>
      <text class="fig-blue" x="390" y="118" font-size="10.5">度=2</text>
      <text class="fig-label" x="167" y="245" text-anchor="middle" font-size="10.5">亲兄弟</text>
      <text class="fig-purple" x="279" y="249" text-anchor="middle" font-size="10.5">堂兄弟</text>
      <text class="fig-title" x="568" y="34" text-anchor="middle">核心术语速查</text>
      <text class="fig-label" x="474" y="63">结点度：a=3，b,d=2，余=0</text>
      <text class="fig-muted" x="474" y="83">树的度 = max&#123;结点度&#125; = 3</text>
      <text class="fig-green" x="474" y="121">叶子结点：c, e, f, g, h（共5个）</text>
      <text class="fig-blue" x="474" y="141">内部结点：b, d（不含根 a）</text>
      <text class="fig-label" x="474" y="179">e 的祖先：a, b；b 的子孙：e, f</text>
      <text class="fig-purple" x="474" y="199">兄弟同双亲；堂兄弟双亲同层</text>
      <text class="fig-orange" x="474" y="236">深度 / 高度 = 最大层次数 = 3</text>
      <text class="fig-muted" x="474" y="253" font-size="10.5">删去根 a → 3 棵子树构成森林</text>
    </g>
  </svg>
  <figcaption>树的基本术语：层次数、结点度与树的度、叶子（绿）与内部结点（蓝）、亲兄弟 vs 堂兄弟</figcaption>
</figure>

树与线性结构的对比：

| | 线性结构 | 树形结构 |
|---|---|---|
| 第一个元素 | 无前驱，唯一 | 根，无双亲，唯一 |
| 最后一个元素 | 无后继，唯一 | 叶子，无孩子，可多个 |
| 其余元素 | 一前驱、一后继 | 一双亲、多孩子 |
| 元素关系 | 一对一 | 一对多 |

### 二叉树的定义与基本形态

二叉树是 $n\ (n \ge 0)$ 个结点的有限集合：或为**空二叉树**，或由**根结点**及两棵**互不相交**的、分别称为**左子树**和**右子树**的二叉树组成。

三个要点：

1. 每个结点**至多两个孩子**，即所有结点的度 $\le 2$；
2. 子树有**左右之分**，次序不能颠倒——即使只有一个孩子，也要说明是左孩子还是右孩子；
3. 根可以有空的左子树或空的右子树，**位置固定但可以为空**。

> **注意**：二叉树**不是树的特例**，两者是不同概念。树中结点只有一个孩子时不分左右，而二叉树必须分。含 2 个结点时：二叉树有 2 种形态（左孩子 / 右孩子），树只有 1 种；含 3 个结点时：二叉树有 5 种形态，树只有 2 种（三层 / 两层）。

二叉树的**五种基本形态**：空二叉树、只有根、根 + 左子树、根 + 右子树、根 + 左右子树。任一二叉树必属其一。

<figure class="cpd-figure not-content" id="wz-w3-fig-2">
  <svg viewBox="0 0 700 286" role="img" aria-label="二叉树的五种基本形态及含 3 个结点时树与二叉树的形态数目本质差异">
    <rect class="fig-box-subtle" x="16" y="14" width="668" height="122" rx="8"/>
    <rect class="fig-box-subtle" x="16" y="146" width="232" height="126" rx="8"/>
    <rect class="fig-box-subtle" x="260" y="146" width="424" height="126" rx="8"/>
    <rect class="fig-box-dashed" x="48" y="64" width="44" height="36" rx="6"/>
    <g class="fig-line">
      <line x1="336" y1="64" x2="306" y2="100"/>
      <line x1="462" y1="64" x2="492" y2="100"/>
      <line x1="606" y1="64" x2="578" y2="100"/>
      <line x1="606" y1="64" x2="634" y2="100"/>
      <line x1="76" y1="190" x2="76" y2="218"/>
      <line x1="76" y1="218" x2="76" y2="246"/>
      <line x1="176" y1="196" x2="152" y2="234"/>
      <line x1="176" y1="196" x2="200" y2="234"/>
      <line x1="312" y1="190" x2="294" y2="218"/>
      <line x1="294" y1="218" x2="276" y2="246"/>
      <line x1="380" y1="190" x2="362" y2="218"/>
      <line x1="362" y1="218" x2="380" y2="246"/>
      <line x1="454" y1="196" x2="432" y2="234"/>
      <line x1="454" y1="196" x2="476" y2="234"/>
      <line x1="538" y1="190" x2="556" y2="218"/>
      <line x1="556" y1="218" x2="538" y2="246"/>
      <line x1="612" y1="190" x2="630" y2="218"/>
      <line x1="630" y1="218" x2="648" y2="246"/>
    </g>
    <g class="fig-line-dashed">
      <line x1="336" y1="64" x2="364" y2="100"/>
      <line x1="462" y1="64" x2="434" y2="100"/>
    </g>
    <circle class="fig-box-accent" cx="196" cy="76" r="14"/>
    <circle class="fig-box-accent" cx="336" cy="64" r="13"/>
    <polygon class="fig-box-blue" points="306,88 286,116 326,116"/>
    <circle class="fig-box-accent" cx="462" cy="64" r="13"/>
    <polygon class="fig-box-orange" points="492,88 472,116 512,116"/>
    <circle class="fig-box-accent" cx="606" cy="64" r="13"/>
    <polygon class="fig-box-blue" points="578,88 558,116 598,116"/>
    <polygon class="fig-box-orange" points="634,88 614,116 654,116"/>
    <g class="fig-box">
      <circle cx="76" cy="190" r="9"/><circle cx="76" cy="218" r="9"/><circle cx="76" cy="246" r="9"/>
      <circle cx="176" cy="196" r="9"/><circle cx="152" cy="234" r="9"/><circle cx="200" cy="234" r="9"/>
    </g>
    <g class="fig-box-blue">
      <circle cx="312" cy="190" r="9"/><circle cx="294" cy="218" r="9"/><circle cx="276" cy="246" r="9"/>
      <circle cx="380" cy="190" r="9"/><circle cx="362" cy="218" r="9"/><circle cx="380" cy="246" r="9"/>
    </g>
    <g class="fig-box-accent">
      <circle cx="454" cy="196" r="9"/><circle cx="432" cy="234" r="9"/><circle cx="476" cy="234" r="9"/>
    </g>
    <g class="fig-box-orange">
      <circle cx="538" cy="190" r="9"/><circle cx="556" cy="218" r="9"/><circle cx="538" cy="246" r="9"/>
      <circle cx="612" cy="190" r="9"/><circle cx="630" cy="218" r="9"/><circle cx="648" cy="246" r="9"/>
    </g>
    <g font-size="11.5" text-anchor="middle">
      <text class="fig-title" x="350" y="32">二叉树的五种基本形态（子树位置固定，单支也必须区分左右）</text>
      <text class="fig-muted" x="70" y="52">① 空树</text>
      <text class="fig-muted" x="70" y="86" font-size="14">∅</text>
      <text class="fig-muted" x="196" y="52">② 仅根结点</text>
      <text class="fig-accent" x="196" y="80">R</text>
      <text class="fig-blue" x="336" y="44">③ 根+左子树</text>
      <text class="fig-accent" x="336" y="68" font-size="11">R</text>
      <text class="fig-blue" x="306" y="111" font-size="10">TL</text>
      <text class="fig-muted" x="366" y="108" font-size="10">∅</text>
      <text class="fig-orange" x="462" y="44">④ 根+右子树</text>
      <text class="fig-accent" x="462" y="68" font-size="11">R</text>
      <text class="fig-muted" x="432" y="108" font-size="10">∅</text>
      <text class="fig-orange" x="492" y="111" font-size="10">TR</text>
      <text class="fig-accent" x="606" y="44">⑤ 根+左右子树</text>
      <text class="fig-accent" x="606" y="68" font-size="11">R</text>
      <text class="fig-blue" x="578" y="111" font-size="10">TL</text>
      <text class="fig-orange" x="634" y="111" font-size="10">TR</text>
      <text class="fig-title" x="132" y="168">含 3 结点的普通树：仅 2 种</text>
      <text class="fig-muted" x="76" y="264" font-size="10.5">单支不分左右</text>
      <text class="fig-muted" x="176" y="264" font-size="10.5">度为 2</text>
      <text class="fig-title" x="472" y="168">含 3 结点的二叉树：共 C₃ = 5 种不同形态</text>
      <text class="fig-blue" x="294" y="264" font-size="10.5">左-左</text>
      <text class="fig-blue" x="372" y="264" font-size="10.5">左-右</text>
      <text class="fig-accent" x="454" y="264" font-size="10.5">左右双支</text>
      <text class="fig-orange" x="547" y="264" font-size="10.5">右-左</text>
      <text class="fig-orange" x="630" y="264" font-size="10.5">右-右</text>
    </g>
  </svg>
  <figcaption>二叉树五种基本形态及与普通树的区别：二叉树严格区分左右孩子，并非“度 ≤ 2 的树”</figcaption>
</figure>

树的术语（度、层次、深度、兄弟、堂兄弟等）对二叉树全部适用。基本操作包括：建立二叉树、先序/中序/后序遍历、求结点总数、求叶子数、求深度、删除结点等。

### 二叉树的性质 1–3

**性质 1**：二叉树的第 $i$ 层上至多有 $2^{i-1}$ 个结点（$i \ge 1$）。

归纳证明：$i=1$ 时只有根，$2^{0}=1$ 成立；设第 $i-1$ 层至多 $2^{i-2}$ 个结点，每个结点至多两个孩子，故第 $i$ 层至多 $2 \times 2^{i-2} = 2^{i-1}$ 个。第 $i$ 层**至少有 1 个**结点（否则不存在第 $i$ 层）。

**性质 2**：深度为 $k$ 的二叉树至多有 $2^k-1$ 个结点（$k \ge 1$）。

由性质 1，逐层最多结点数构成等比数列：

$$
\sum_{i=1}^{k} 2^{i-1} = 2^{k}-1
$$

深度为 $k$ 的二叉树**至少有** $k$ 个结点（每层一个，即单支树）。

**性质 3**：对任何一棵二叉树，若叶子数为 $n_0$、度为 2 的结点数为 $n_2$，则

$$
n_0 = n_2 + 1
$$

证明（两种数边法）：设结点总数 $n=n_0+n_1+n_2$，边数 $e$。

- 自下而上：除根外每个结点都连向双亲，$e = n-1$；
- 自上而下：度为 2 的结点发出 2 条边，度为 1 的发出 1 条，叶子发出 0 条，$e = 2n_2+n_1$。

两式相等：$n_0+n_1+n_2-1 = 2n_2+n_1$，约去 $n_1$ 得 $n_0 = n_2+1$。

> **★考点**：性质 3 的价值在“两种数边法”的分析思路，由此可推出树的许多其他性质。

<figure class="cpd-figure not-content" id="wz-w3-fig-3">
  <svg viewBox="0 0 700 256" role="img" aria-label="二叉树性质 3 两种数边法可视化证明：叶子数 n0 等于度为 2 的结点数 n2 加 1">
    <rect class="fig-box-subtle" x="16" y="14" width="286" height="228" rx="8"/>
    <rect class="fig-box-subtle" x="314" y="14" width="370" height="228" rx="8"/>
    <g class="fig-line-accent">
      <line x1="158" y1="58" x2="96" y2="116"/>
      <line x1="158" y1="58" x2="220" y2="116"/>
      <line x1="96" y1="116" x2="60" y2="176"/>
      <line x1="96" y1="116" x2="132" y2="176"/>
      <line x1="220" y1="116" x2="252" y2="176"/>
    </g>
    <circle class="fig-box-accent" cx="158" cy="58" r="16"/>
    <circle class="fig-box-accent" cx="96" cy="116" r="16"/>
    <circle class="fig-box-blue" cx="220" cy="116" r="16"/>
    <g class="fig-box-green">
      <circle cx="60" cy="176" r="16"/>
      <circle cx="132" cy="176" r="16"/>
      <circle cx="252" cy="176" r="16"/>
    </g>
    <rect class="fig-box" x="328" y="44" width="342" height="54" rx="6"/>
    <rect class="fig-box" x="328" y="106" width="342" height="54" rx="6"/>
    <rect class="fig-box-accent" x="328" y="168" width="342" height="62" rx="6"/>
    <g font-size="12" text-anchor="middle">
      <text class="fig-title" x="159" y="34">实例统计（总结点 n=6，总边数 e=5）</text>
      <text class="fig-accent" x="158" y="62">A</text>
      <text class="fig-accent" x="96" y="120">B</text>
      <text class="fig-blue" x="220" y="120">C</text>
      <text class="fig-green" x="60" y="180">D</text>
      <text class="fig-green" x="132" y="180">E</text>
      <text class="fig-green" x="252" y="180">F</text>
      <text class="fig-accent" x="194" y="54" font-size="10.5">度=2</text>
      <text class="fig-accent" x="62" y="112" font-size="10.5">度=2</text>
      <text class="fig-blue" x="254" y="112" font-size="10.5">度=1</text>
      <text class="fig-muted" x="159" y="214" font-size="11">n₂=2（A,B）  n₁=1（C）  n₀=3（D,E,F）</text>
      <text class="fig-green" x="159" y="232" font-size="11.5">验证：n₀ = 3 = 2 + 1 = n₂ + 1</text>
      <text class="fig-title" x="499" y="34">“两种数边法”核心推导</text>
    </g>
    <g font-size="11.5">
      <text class="fig-blue" x="340" y="64">① 自下而上看双亲：除根外每结点头顶 1 条边</text>
      <text class="fig-label" x="356" y="85">e = n - 1 = (n₀ + n₁ + n₂) - 1</text>
      <text class="fig-orange" x="340" y="126">② 自上而下看孩子：度为 k 的结点发出 k 条边</text>
      <text class="fig-label" x="356" y="147">e = 2·n₂ + 1·n₁ + 0·n₀ = 2n₂ + n₁</text>
      <text class="fig-accent" x="340" y="189" font-size="9.5">联立消去 e 与 n₁：n₀ + n₁ + n₂ - 1 = 2n₂ + n₁ ⇒ n₀ = n₂ + 1</text>
      <text class="fig-muted" x="340" y="214" font-size="10">推广至 m 叉树：n₀ = 1 + n₂ + 2n₃ + … + (m-1)nₘ（增一度多生叶）</text>
    </g>
  </svg>
  <figcaption>性质 3（n₀ = n₂ + 1）两种数边法图解：自下而上按入边计 n-1，自上而下按出度计 2n₂+n₁</figcaption>
</figure>

### 满二叉树与完全二叉树

**满二叉树**：深度为 $k$ 且含 $2^k-1$ 个结点的二叉树，即每一层都达到最大结点数。

特征：每层都满；叶子只出现在最后一层；按“从上到下、从左到右”从 1 开始编号后，$1 \sim 2^k-1$ 每个位置都有结点，无空位。同样深度下，满二叉树的结点数最多、叶子数最多。

**完全二叉树**：深度为 $k$、含 $n$ 个结点的二叉树，当且仅当其每个结点都与**同深度满二叉树中编号 $1 \sim n$ 的结点一一对应**。

等价判定：从满二叉树的**最后一个结点开始连续删去**若干结点，得到的都是完全二叉树；若删除不连续（中间留下空位），则不是。

特征：

- 叶子只可能出现在**最后两层**；
- 对任一结点，若其右子树最大层次为 $i$，则左子树最大层次只能是 $i$ 或 $i+1$，即左右子树深度差不超过 1；
- 满二叉树一定是完全二叉树，完全二叉树不一定是满二叉树。

判断时最可靠的方法：按满二叉树编号，看编号序列是否为 $1 \sim n$ 的连续前缀。

### 完全二叉树的性质 4、5

**性质 4**：具有 $n$ 个结点的完全二叉树深度为

$$
k = \lfloor \log_2 n \rfloor + 1
$$

其中 $\lfloor x \rfloor$ 表示不大于 $x$ 的最大整数。

推导：$k$ 层完全二叉树的结点数满足 $2^{k-1} \le n \le 2^{k}-1$，取以 2 为底的对数得 $k-1 \le \log_2 n < k$，故 $k = \lfloor \log_2 n \rfloor + 1$。例：$n=12$，$\lfloor \log_2 12 \rfloor + 1 = 3+1 = 4$ 层。

**性质 5**：对完全二叉树中编号为 $i$ 的结点（根编号为 1）：

- 双亲编号为 $\lfloor i/2 \rfloor$（$i=1$ 时无双亲）；
- 左孩子编号为 $2i$，右孩子编号为 $2i+1$（仅当编号 $\le n$ 时该孩子存在）。

证明思路：归纳。完全二叉树中间没有空位，编号 $i$ 的两个孩子为 $2i,2i+1$，则编号 $i+1$ 的两个孩子必为 $2i+2,2i+3$，恰好接续。

> **注意**：性质 5 按编号从 1 开始。顺序存储时若把根放在数组下标 0，则编号 $i$ 存于下标 $i-1$，于是下标 $j$ 的左孩子为 $2j+1$、右孩子为 $2j+2$。性质 5 是顺序存储中“由下标直接找双亲/孩子”的依据。

<figure class="cpd-figure not-content" id="wz-w3-fig-4">
  <svg viewBox="0 0 700 286" role="img" aria-label="满二叉树、完全二叉树与非完全二叉树按层连续编号对比及性质 4、5 下标换算">
    <rect class="fig-box-subtle" x="16" y="14" width="212" height="186" rx="8"/>
    <rect class="fig-box-subtle" x="240" y="14" width="218" height="186" rx="8"/>
    <rect class="fig-box-subtle" x="470" y="14" width="214" height="186" rx="8"/>
    <rect class="fig-box-subtle" x="16" y="210" width="668" height="62" rx="8"/>
    <g class="fig-line">
      <line x1="122" y1="58" x2="78" y2="108"/><line x1="122" y1="58" x2="166" y2="108"/>
      <line x1="78" y1="108" x2="54" y2="158"/><line x1="78" y1="108" x2="102" y2="158"/>
      <line x1="166" y1="108" x2="142" y2="158"/><line x1="166" y1="108" x2="190" y2="158"/>
      <line x1="349" y1="58" x2="305" y2="108"/><line x1="349" y1="58" x2="393" y2="108"/>
      <line x1="305" y1="108" x2="281" y2="158"/><line x1="305" y1="108" x2="329" y2="158"/>
      <line x1="393" y1="108" x2="369" y2="158"/>
      <line x1="577" y1="58" x2="533" y2="108"/><line x1="577" y1="58" x2="621" y2="108"/>
      <line x1="533" y1="108" x2="509" y2="158"/><line x1="533" y1="108" x2="557" y2="158"/>
      <line x1="621" y1="108" x2="645" y2="158"/>
    </g>
    <g class="fig-line-dashed">
      <line x1="393" y1="108" x2="411" y2="145"/>
      <line x1="621" y1="108" x2="603" y2="145"/>
    </g>
    <g class="fig-box-green">
      <circle cx="122" cy="58" r="14"/><circle cx="78" cy="108" r="14"/><circle cx="166" cy="108" r="14"/>
      <circle cx="54" cy="158" r="14"/><circle cx="102" cy="158" r="14"/><circle cx="142" cy="158" r="14"/><circle cx="190" cy="158" r="14"/>
    </g>
    <g class="fig-box-blue">
      <circle cx="349" cy="58" r="14"/><circle cx="305" cy="108" r="14"/><circle cx="393" cy="108" r="14"/>
      <circle cx="281" cy="158" r="14"/><circle cx="329" cy="158" r="14"/><circle cx="369" cy="158" r="14"/>
    </g>
    <circle class="fig-box-dashed" cx="417" cy="158" r="14"/>
    <g class="fig-box">
      <circle cx="577" cy="58" r="14"/><circle cx="533" cy="108" r="14"/><circle cx="621" cy="108" r="14"/>
      <circle cx="509" cy="158" r="14"/><circle cx="557" cy="158" r="14"/>
    </g>
    <circle class="fig-box-red" cx="597" cy="158" r="14"/>
    <circle class="fig-box-orange" cx="645" cy="158" r="14"/>
    <g font-size="11.5" text-anchor="middle">
      <text class="fig-green" x="122" y="34">满二叉树（1&#126;2³-1 全满）</text>
      <text class="fig-green" x="122" y="62">1</text>
      <text class="fig-green" x="78" y="112">2</text><text class="fig-green" x="166" y="112">3</text>
      <text class="fig-green" x="54" y="162">4</text><text class="fig-green" x="102" y="162">5</text>
      <text class="fig-green" x="142" y="162">6</text><text class="fig-green" x="190" y="162">7</text>
      <text class="fig-muted" x="122" y="188" font-size="10.5">叶子全在最底层</text>
      <text class="fig-blue" x="349" y="34">完全二叉树（连续前缀 1&#126;6）</text>
      <text class="fig-blue" x="349" y="62">1</text>
      <text class="fig-blue" x="305" y="112">2</text><text class="fig-blue" x="393" y="112">3</text>
      <text class="fig-blue" x="281" y="162">4</text><text class="fig-blue" x="329" y="162">5</text>
      <text class="fig-blue" x="369" y="162">6</text><text class="fig-muted" x="417" y="162">删</text>
      <text class="fig-muted" x="349" y="188" font-size="10.5">度为 1 结点至多 1 个（且仅有左孩）</text>
      <text class="fig-red" x="577" y="34">非完全二叉树（缺 6 存 7）</text>
      <text class="fig-label" x="577" y="62">1</text>
      <text class="fig-label" x="533" y="112">2</text><text class="fig-label" x="621" y="112">3</text>
      <text class="fig-label" x="509" y="162">4</text><text class="fig-label" x="557" y="162">5</text>
      <text class="fig-red" x="597" y="162">缺</text><text class="fig-orange" x="645" y="162">7</text>
      <text class="fig-red" x="577" y="188" font-size="10.5">编号不连续，3 无左孩有右孩</text>
    </g>
    <g font-size="11.5">
      <text class="fig-accent" x="30" y="232" font-size="10.5">性质 4：深度 k = ⌊log₂n⌋ + 1（如 n=6 时 k=3）</text>
      <text class="fig-blue" x="360" y="232" font-size="10.5">性质 5（根为 1）：双亲 ⌊i/2⌋，左孩 2i，右孩 2i+1</text>
      <text class="fig-orange" x="30" y="256">408 高频换算（数组 bt[0] 存根，下标 j = i - 1）：双亲 ⌊(j-1)/2⌋，左孩 2j + 1，右孩 2j + 2</text>
    </g>
  </svg>
  <figcaption>满二叉树、完全二叉树与非完全二叉树对比：完全二叉树编号必为 1&#126;n 连续前缀，支撑下标直接寻址</figcaption>
</figure>

### 二叉树的顺序存储结构

用一组**连续空间（数组）**存放结点：先按满二叉树方式（从上到下、从左到右）给每个位置编号，再**以编号作为数组下标**把结点存到对应位置。

```c
#define MAXTSIZE 100
typedef TElemType SqBiTree[MAXTSIZE];
SqBiTree bt;                 // bt[0] 为根
```

非完全二叉树中，缺失的结点位置**必须空出**（存空值或 0），不能把后面的结点前移；否则数组只能表示一棵满二叉树，原树的双亲/孩子关系无法恢复。

顺序存储的优缺点：

| 优点 | 缺点 |
|---|---|
| 双亲、孩子关系隐含在下标中，无需指针域，存储密度高、操作方便 | 数组**定长**，结点数变化大时不合适 |
| 完全二叉树、满二叉树几乎不浪费空间 | 非完全二叉树要为空结点留位置，浪费空间 |

最坏情况是**单支树**（每个结点只有左孩子或只有右孩子）：$k$ 个结点需要 $2^k-1$ 个位置，如 5 个结点的单支树要 31 个位置，存储密度仅 $5/31$。因此顺序存储适合**满二叉树和完全二叉树**（堆排序中的堆就用这种结构）。

<figure class="cpd-figure not-content" id="wz-w3-fig-5">
  <svg viewBox="0 0 700 258" role="img" aria-label="二叉树顺序存储数组布局对比：完全二叉树紧凑无浪费与右单支树指数级空间浪费">
    <rect class="fig-box-subtle" x="16" y="14" width="668" height="104" rx="8"/>
    <rect class="fig-box-subtle" x="16" y="128" width="668" height="116" rx="8"/>
    <g class="fig-box-green">
      <rect x="200" y="54" width="44" height="32" rx="4"/><rect x="248" y="54" width="44" height="32" rx="4"/>
      <rect x="296" y="54" width="44" height="32" rx="4"/><rect x="344" y="54" width="44" height="32" rx="4"/>
      <rect x="392" y="54" width="44" height="32" rx="4"/><rect x="440" y="54" width="44" height="32" rx="4"/>
    </g>
    <g class="fig-line">
      <line x1="56" y1="158" x2="78" y2="178"/>
      <line x1="78" y1="178" x2="100" y2="198"/>
      <line x1="100" y1="198" x2="122" y2="218"/>
    </g>
    <g class="fig-box-orange">
      <circle cx="56" cy="158" r="10"/><circle cx="78" cy="178" r="10"/>
      <circle cx="100" cy="198" r="10"/><circle cx="122" cy="218" r="10"/>
    </g>
    <g class="fig-box-accent">
      <rect x="196" y="170" width="28" height="30" rx="3"/>
      <rect x="260" y="170" width="28" height="30" rx="3"/>
      <rect x="388" y="170" width="28" height="30" rx="3"/>
      <rect x="644" y="170" width="28" height="30" rx="3"/>
    </g>
    <g class="fig-box-dashed">
      <rect x="228" y="170" width="28" height="30" rx="3"/>
      <rect x="292" y="170" width="28" height="30" rx="3"/><rect x="324" y="170" width="28" height="30" rx="3"/><rect x="356" y="170" width="28" height="30" rx="3"/>
      <rect x="420" y="170" width="28" height="30" rx="3"/><rect x="452" y="170" width="28" height="30" rx="3"/><rect x="484" y="170" width="28" height="30" rx="3"/>
      <rect x="516" y="170" width="28" height="30" rx="3"/><rect x="548" y="170" width="28" height="30" rx="3"/><rect x="580" y="170" width="28" height="30" rx="3"/><rect x="612" y="170" width="28" height="30" rx="3"/>
    </g>
    <g font-size="11.5">
      <text class="fig-title" x="30" y="36">① 完全二叉树顺序存储（n = 6）：紧凑连续，存储密度 100%（适合二叉堆）</text>
      <text class="fig-green" x="30" y="75">树编号 1&#126;6 连续：</text>
      <text class="fig-muted" x="504" y="75">无任何空洞，下标直接算父子</text>
      <text class="fig-title" x="30" y="148">② k = 4 右单支树顺序存储：缺失位置必须留空（∧），需要 2⁴ - 1 = 15 个单元！</text>
      <text class="fig-red" x="196" y="224" font-size="10">仅下标 1, 3, 7, 15 有效（共 4 个），其余 11 格全空；若压缩前移则退化为满二叉树，父子关系丢失</text>
    </g>
    <g font-size="11" text-anchor="middle">
      <text class="fig-green" x="222" y="74">A</text><text class="fig-green" x="270" y="74">B</text><text class="fig-green" x="318" y="74">C</text>
      <text class="fig-green" x="366" y="74">D</text><text class="fig-green" x="414" y="74">E</text><text class="fig-green" x="462" y="74">F</text>
      <text class="fig-muted" x="222" y="102" font-size="10">[1]</text><text class="fig-muted" x="270" y="102" font-size="10">[2]</text><text class="fig-muted" x="318" y="102" font-size="10">[3]</text>
      <text class="fig-muted" x="366" y="102" font-size="10">[4]</text><text class="fig-muted" x="414" y="102" font-size="10">[5]</text><text class="fig-muted" x="462" y="102" font-size="10">[6]</text>
      <text class="fig-orange" x="56" y="162" font-size="9.5">A</text><text class="fig-orange" x="78" y="182" font-size="9.5">B</text>
      <text class="fig-orange" x="100" y="202" font-size="9.5">C</text><text class="fig-orange" x="122" y="222" font-size="9.5">D</text>
      <text class="fig-accent" x="210" y="189">A</text><text class="fig-muted" x="242" y="189">∧</text><text class="fig-accent" x="274" y="189">B</text>
      <text class="fig-muted" x="306" y="189">∧</text><text class="fig-muted" x="338" y="189">∧</text><text class="fig-muted" x="370" y="189">∧</text><text class="fig-accent" x="402" y="189">C</text>
      <text class="fig-muted" x="434" y="189">∧</text><text class="fig-muted" x="466" y="189">∧</text><text class="fig-muted" x="498" y="189">∧</text><text class="fig-muted" x="530" y="189">∧</text>
      <text class="fig-muted" x="562" y="189">∧</text><text class="fig-muted" x="594" y="189">∧</text><text class="fig-muted" x="626" y="189">∧</text><text class="fig-accent" x="658" y="189">D</text>
      <text class="fig-muted" x="210" y="165" font-size="9.5">1</text><text class="fig-muted" x="274" y="165" font-size="9.5">3</text>
      <text class="fig-muted" x="402" y="165" font-size="9.5">7</text><text class="fig-muted" x="658" y="165" font-size="9.5">15</text>
    </g>
  </svg>
  <figcaption>顺序存储的极端对比：完全二叉树零浪费，k 层单支树需 2ᵏ-1 个单元（存储密度仅 k/(2ᵏ-1)）</figcaption>
</figure>

### 二叉链表与三叉链表

**二叉链表**：每个结点含数据域和两个指针域，分别指向左孩子、右孩子。

```c
typedef struct BiTNode {
    TElemType data;
    struct BiTNode *lchild, *rchild;
} BiTNode, *BiTree;
```

结构体内部引用自身，是**递归（嵌套）定义**，与单链表结点定义同理。整棵树用指向根结点的指针 `T` 表示。

**三叉链表**：在二叉链表上增加一个指向双亲的指针域 `parent`。适合需要频繁“由孩子找双亲”的场合；找孩子用二叉链表即可，因为双亲只有一个，所以三叉链表只加一个指针域。

空指针域计数：$n$ 个结点的二叉链表共有 $2n$ 个指针域，其中 $n-1$ 个用于指向孩子（每个非根结点唯一对应一条双亲—孩子边），故

$$
\text{空指针域} = 2n-(n-1) = n+1
$$

这些空指针域正是线索二叉树可以利用的资源。

> **注意**：二叉链表找左右孩子是 $O(1)$，找双亲需遍历整棵树；要快速找双亲就用三叉链表。

<figure class="cpd-figure not-content" id="wz-w3-fig-6">
  <svg viewBox="0 0 700 278" role="img" aria-label="二叉链表与三叉链表结点结构对比及 n 个结点含 n+1 个空指针域的可视化证明">
    <defs>
      <marker id="wz-w3-arr-6" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="14" width="268" height="250" rx="8"/>
    <rect class="fig-box-subtle" x="296" y="14" width="388" height="250" rx="8"/>
    <g class="fig-line" marker-end="url(#wz-w3-arr-6)">
      <line x1="464" y1="68" x2="412" y2="108"/>
      <line x1="516" y1="68" x2="568" y2="108"/>
      <line x1="428" y1="132" x2="472" y2="178"/>
    </g>
    <rect class="fig-box-blue" x="34" y="48" width="76" height="28" rx="4"/>
    <rect class="fig-box-accent" x="110" y="48" width="80" height="28" rx="4"/>
    <rect class="fig-box-blue" x="190" y="48" width="76" height="28" rx="4"/>
    <rect class="fig-box-blue" x="28" y="114" width="58" height="28" rx="4"/>
    <rect class="fig-box-accent" x="86" y="114" width="58" height="28" rx="4"/>
    <rect class="fig-box-purple" x="144" y="114" width="68" height="28" rx="4"/>
    <rect class="fig-box-blue" x="212" y="114" width="58" height="28" rx="4"/>
    <rect class="fig-box" x="28" y="168" width="242" height="82" rx="6"/>
    <rect class="fig-box-blue" x="452" y="44" width="24" height="24" rx="2"/>
    <rect class="fig-box-accent" x="476" y="44" width="28" height="24" rx="2"/>
    <rect class="fig-box-blue" x="504" y="44" width="24" height="24" rx="2"/>
    <rect class="fig-box-orange" x="368" y="108" width="24" height="24" rx="2"/>
    <rect class="fig-box-accent" x="392" y="108" width="28" height="24" rx="2"/>
    <rect class="fig-box-blue" x="420" y="108" width="24" height="24" rx="2"/>
    <rect class="fig-box-orange" x="546" y="108" width="24" height="24" rx="2"/>
    <rect class="fig-box-accent" x="570" y="108" width="28" height="24" rx="2"/>
    <rect class="fig-box-orange" x="598" y="108" width="24" height="24" rx="2"/>
    <rect class="fig-box-orange" x="452" y="178" width="24" height="24" rx="2"/>
    <rect class="fig-box-accent" x="476" y="178" width="28" height="24" rx="2"/>
    <rect class="fig-box-orange" x="504" y="178" width="24" height="24" rx="2"/>
    <rect class="fig-box" x="310" y="214" width="360" height="40" rx="6"/>
    <g font-size="11.5" text-anchor="middle">
      <text class="fig-title" x="150" y="34">二叉链表 vs 三叉链表结点</text>
      <text class="fig-blue" x="72" y="66">lchild</text>
      <text class="fig-accent" x="150" y="66">data</text>
      <text class="fig-blue" x="228" y="66">rchild</text>
      <text class="fig-muted" x="150" y="98" font-size="10.5">↓ 增加双亲域构成三叉链表</text>
      <text class="fig-blue" x="57" y="132">lchild</text>
      <text class="fig-accent" x="115" y="132">data</text>
      <text class="fig-purple" x="178" y="132">parent</text>
      <text class="fig-blue" x="241" y="132">rchild</text>
      <text class="fig-title" x="490" y="32">二叉链表空指针域计数（实例 n = 4）</text>
      <text class="fig-blue" x="464" y="60">•</text><text class="fig-accent" x="490" y="60">A</text><text class="fig-blue" x="516" y="60">•</text>
      <text class="fig-orange" x="380" y="124">∧</text><text class="fig-accent" x="406" y="124">B</text><text class="fig-blue" x="432" y="124">•</text>
      <text class="fig-orange" x="558" y="124">∧</text><text class="fig-accent" x="584" y="124">C</text><text class="fig-orange" x="610" y="124">∧</text>
      <text class="fig-orange" x="464" y="194">∧</text><text class="fig-accent" x="490" y="194">D</text><text class="fig-orange" x="516" y="194">∧</text>
    </g>
    <g font-size="11">
      <text class="fig-label" x="38" y="190">• 二叉链表找孩子 O(1)，找双亲 O(n)</text>
      <text class="fig-purple" x="38" y="212">• 三叉链表找双亲 O(1)（双向直达）</text>
      <text class="fig-muted" x="38" y="234">• 整棵树由根指针 BiTree T 唯一标识</text>
      <text class="fig-label" x="322" y="231">总指针域 = 2n = 8；非空分支指针 = n - 1 = 3（蓝实线）</text>
      <text class="fig-orange" x="322" y="248">空指针域（∧）= 2n - (n - 1) = n + 1 = 5（线索化利用资源）</text>
    </g>
  </svg>
  <figcaption>二叉链表与三叉链表结构对比：n 个结点的二叉链表必含 n+1 个空指针域（橙色 ∧）</figcaption>
</figure>

### 遍历的定义与三种次序

**遍历**：沿某条搜索路径访问二叉树中每个结点**一次且仅一次**。“访问”可做任意处理（输出、比较、修改等），通常不改变树的结构（不插入、不删除）。

遍历的作用：把非线性的树结构转换成结点的**线性序列**，是二叉树其他运算（建树、复制、计数、求深度等）的基础和核心。

把二叉树看成三部分：根 $D$、左子树 $L$、右子树 $R$。规定**先左后右**，则只有三种次序：

| 名称 | 次序 | 别名 |
|---|---|---|
| 先序遍历 | $D \to L \to R$ | 先根遍历、前序遍历 |
| 中序遍历 | $L \to D \to R$ | 中根遍历 |
| 后序遍历 | $L \to R \to D$ | 后根遍历 |

（若不规定先左后右，$D,L,R$ 的全排列有 6 种，后三种与前三种镜像对称。）

**统一的访问路径**：三种算法走的是同一条路径——从根出发，沿“根→左子树→右子树”绕行，**每个结点被路过三次**。第 1 次路过就访问是**先序**，第 2 次路过访问是**中序**，第 3 次路过访问是**后序**。因此三种递归算法去掉“访问根”语句后完全相同，只是访问时机不同。

复杂度：三种遍历时间均为 $O(n)$（每个结点访问一次）；空间为递归栈，最坏（单支树）$O(n)$。

表达式树的应用：叶子为操作数、分支结点为运算符。先序序列即**前缀表达式**，中序序列即**中缀表达式**，后序序列即**后缀表达式**。由中缀表达式构造表达式树后作后序遍历，即可得到后缀表达式。

<figure class="cpd-figure not-content" id="wz-w3-fig-7">
  <svg viewBox="0 0 700 282" role="img" aria-label="二叉树遍历的欧拉环游三次路过统一路径与表达式树的前缀、中缀、后缀序列应用">
    <defs>
      <marker id="wz-w3-arr-7" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="14" width="356" height="254" rx="8"/>
    <rect class="fig-box-subtle" x="384" y="14" width="300" height="254" rx="8"/>
    <path class="fig-line-dashed" stroke="var(--sl-color-purple)" marker-end="url(#wz-w3-arr-7)" d="M 164 46 C 118 68, 86 102, 82 142 C 78 176, 126 178, 136 144 C 154 106, 184 88, 196 90 C 208 88, 238 106, 256 144 C 266 178, 314 176, 310 142 C 306 102, 274 68, 228 46"/>
    <g class="fig-line">
      <line x1="196" y1="66" x2="112" y2="142"/>
      <line x1="196" y1="66" x2="280" y2="142"/>
      <line x1="534" y1="62" x2="478" y2="114"/>
      <line x1="534" y1="62" x2="590" y2="114"/>
      <line x1="478" y1="114" x2="442" y2="166"/>
      <line x1="478" y1="114" x2="514" y2="166"/>
    </g>
    <circle class="fig-box-accent" cx="196" cy="66" r="18"/>
    <circle class="fig-box-blue" cx="112" cy="142" r="18"/>
    <circle class="fig-box-green" cx="280" cy="142" r="18"/>
    <circle class="fig-dot" cx="176" cy="66" r="3.5"/>
    <circle class="fig-dot" cx="196" cy="86" r="3.5"/>
    <circle class="fig-dot" cx="216" cy="66" r="3.5"/>
    <circle class="fig-dot" cx="92" cy="142" r="3.5"/>
    <circle class="fig-dot" cx="112" cy="162" r="3.5"/>
    <circle class="fig-dot" cx="132" cy="142" r="3.5"/>
    <circle class="fig-dot" cx="260" cy="142" r="3.5"/>
    <circle class="fig-dot" cx="280" cy="162" r="3.5"/>
    <circle class="fig-dot" cx="300" cy="142" r="3.5"/>
    <rect class="fig-box" x="28" y="196" width="332" height="60" rx="6"/>
    <circle class="fig-box-accent" cx="534" cy="62" r="15"/>
    <circle class="fig-box-orange" cx="478" cy="114" r="15"/>
    <circle class="fig-box-green" cx="590" cy="114" r="15"/>
    <circle class="fig-box-green" cx="442" cy="166" r="15"/>
    <circle class="fig-box-green" cx="514" cy="166" r="15"/>
    <rect class="fig-box" x="396" y="192" width="276" height="64" rx="6"/>
    <g font-size="12" text-anchor="middle">
      <text class="fig-title" x="194" y="34">统一绕行路径：每结点路过 3 次</text>
      <text class="fig-accent" x="196" y="70">D</text>
      <text class="fig-blue" x="112" y="146">L</text>
      <text class="fig-green" x="280" y="146">R</text>
      <text class="fig-accent" x="158" y="68" font-size="10.5">①</text>
      <text class="fig-blue" x="196" y="102" font-size="10.5">②</text>
      <text class="fig-green" x="234" y="68" font-size="10.5">③</text>
      <text class="fig-accent" x="76" y="146" font-size="10.5">①</text>
      <text class="fig-blue" x="112" y="178" font-size="10.5">②</text>
      <text class="fig-green" x="148" y="146" font-size="10.5">③</text>
      <text class="fig-accent" x="244" y="146" font-size="10.5">①</text>
      <text class="fig-blue" x="280" y="178" font-size="10.5">②</text>
      <text class="fig-green" x="316" y="146" font-size="10.5">③</text>
      <text class="fig-title" x="534" y="34">表达式树：(a + b) * c</text>
      <text class="fig-accent" x="534" y="67">*</text>
      <text class="fig-orange" x="478" y="119">+</text>
      <text class="fig-green" x="590" y="119">c</text>
      <text class="fig-green" x="442" y="171">a</text>
      <text class="fig-green" x="514" y="171">b</text>
    </g>
    <g font-size="11">
      <text class="fig-accent" x="40" y="216">① 左侧第1次路过访问 → 先序（D L R）</text>
      <text class="fig-blue" x="40" y="233">② 底部第2次路过访问 → 中序（L D R）</text>
      <text class="fig-green" x="40" y="250">③ 右侧第3次路过访问 → 后序（L R D）</text>
      <text class="fig-accent" x="408" y="212">先序（波兰式/前缀）：* + a b c</text>
      <text class="fig-blue" x="408" y="229">中序（中缀需添括号）：(a + b) * c</text>
      <text class="fig-green" x="408" y="246">后序（逆波兰/后缀）：a b + c *</text>
    </g>
  </svg>
  <figcaption>三种遍历统一绕行路径（①先序 ②中序 ③后序）与表达式树前/中/后缀序列对应</figcaption>
</figure>

### 三种递归遍历算法

```c
void PreOrder(BiTree T) {          // 先序：根 左 右
    if (T) {
        visit(T);
        PreOrder(T->lchild);
        PreOrder(T->rchild);
    }
}

void InOrder(BiTree T) {           // 中序：左 根 右
    if (T) {
        InOrder(T->lchild);
        visit(T);
        InOrder(T->rchild);
    }
}

void PostOrder(BiTree T) {         // 后序：左 右 根
    if (T) {
        PostOrder(T->lchild);
        PostOrder(T->rchild);
        visit(T);
    }
}
```

执行要点：每层调用先判空，空则立即返回；否则把“根、左、右”分解为规模更小的同类问题，递归调用自身，当前层未执行完就进入下一层，**下一层返回后从离开处继续执行**。

例：只有三个结点 a（根）、b（左）、c（右）时，先序为 `a b c`，中序为 `b a c`，后序为 `b c a`。

<figure class="cpd-figure not-content" id="wz-fig-13">
  <svg viewBox="0 0 700 264" role="img" aria-label="7 结点满二叉树与先序、中序、后序、层序四种遍历序列分块对照">
    <rect class="fig-box-subtle" x="16" y="14" width="308" height="236" rx="8"/>
    <rect class="fig-box-subtle" x="336" y="14" width="348" height="236" rx="8"/>
    <g class="fig-line-dashed">
      <line x1="36" y1="62" x2="306" y2="62"/>
      <line x1="36" y1="126" x2="306" y2="126"/>
      <line x1="36" y1="190" x2="306" y2="190"/>
    </g>
    <g class="fig-line">
      <line x1="170" y1="62" x2="104" y2="126"/>
      <line x1="170" y1="62" x2="236" y2="126"/>
      <line x1="104" y1="126" x2="70" y2="190"/>
      <line x1="104" y1="126" x2="138" y2="190"/>
      <line x1="236" y1="126" x2="202" y2="190"/>
      <line x1="236" y1="126" x2="270" y2="190"/>
    </g>
    <circle class="fig-box-accent" cx="170" cy="62" r="17"/>
    <circle class="fig-box-blue" cx="104" cy="126" r="17"/>
    <circle class="fig-box-green" cx="236" cy="126" r="17"/>
    <g class="fig-box-blue">
      <circle cx="70" cy="190" r="16"/><circle cx="138" cy="190" r="16"/>
    </g>
    <g class="fig-box-green">
      <circle cx="202" cy="190" r="16"/><circle cx="270" cy="190" r="16"/>
    </g>
    <rect class="fig-box" x="350" y="46" width="320" height="44" rx="6"/>
    <rect class="fig-box" x="350" y="98" width="320" height="44" rx="6"/>
    <rect class="fig-box" x="350" y="150" width="320" height="44" rx="6"/>
    <rect class="fig-box" x="350" y="202" width="320" height="36" rx="6"/>
    <g font-size="13" text-anchor="middle">
      <text class="fig-title" x="170" y="34" font-size="12">7 结点满二叉树（根 A，左蓝右绿）</text>
      <text class="fig-accent" x="170" y="67">A</text>
      <text class="fig-blue" x="104" y="131">B</text><text class="fig-green" x="236" y="131">C</text>
      <text class="fig-blue" x="70" y="195">D</text><text class="fig-blue" x="138" y="195">E</text>
      <text class="fig-green" x="202" y="195">F</text><text class="fig-green" x="270" y="195">G</text>
      <text class="fig-muted" x="170" y="232" font-size="11">时间 O(n)，递归栈空间最坏 O(n)</text>
      <text class="fig-title" x="510" y="34" font-size="12">四种遍历序列与子树块切分</text>
    </g>
    <g font-size="11.5">
      <text class="fig-accent" x="362" y="65">先序（D L R）：[A]  [B D E]  [C F G]</text>
      <text class="fig-muted" x="362" y="83" font-size="10.5">首元素必为整棵树之根</text>
      <text class="fig-blue" x="362" y="117">中序（L D R）：[D B E]  [A]  [F C G]</text>
      <text class="fig-muted" x="362" y="135" font-size="10.5">根将序列一分为二：左子树 | 根 | 右子树</text>
      <text class="fig-green" x="362" y="169">后序（L R D）：[D E B]  [F G C]  [A]</text>
      <text class="fig-muted" x="362" y="187" font-size="10.5">末元素必为整棵树之根</text>
      <text class="fig-purple" x="362" y="224">层序（逐层左→右）：A  |  B C  |  D E F G</text>
    </g>
  </svg>
  <figcaption>7 结点满二叉树与四种遍历序列对照：注意根 [A]、左子树 [B,D,E] 与右子树 [C,F,G] 的相对位置</figcaption>
</figure>

| 步 | 先序 | 中序 | 后序 |
|:---:|:---:|:---:|:---:|
| 1 | A | D | D |
| 2 | B | B | E |
| 3 | D | E | B |
| 4 | E | A | F |
| 5 | C | F | G |
| 6 | F | C | C |
| 7 | G | G | A |

### 由遍历序列确定二叉树

结点值互异时，一棵二叉树的中序、先序、后序序列都是唯一的；反过来：

| 已知序列 | 能否唯一确定二叉树 |
|---|---|
| 先序 + 中序 | 能 |
| 后序 + 中序 | 能 |
| 先序 + 后序 | **不能**（无法区分只有一个孩子时是左还是右） |

还原方法（以先序 + 中序为例）：

1. 先序序列的**第一个**结点是整棵树的根；
2. 在中序序列中找到该根，其**左边**全部结点属于左子树，**右边**全部结点属于右子树；
3. 左子树结点个数为 $m$，则在先序序列中根之后的 $m$ 个结点是左子树的先序序列，其余是右子树的先序序列；
4. 对左右子树分别重复 1–3，直到序列为空。

后序 + 中序同理，只是根取后序序列的**最后一个**结点，且后序中“左子树序列 | 右子树序列 | 根”的切分位置由中序的左右结点个数决定。

<figure class="cpd-figure not-content" id="wz-w3-fig-8">
  <svg viewBox="0 0 700 282" role="img" aria-label="由先序加中序递归切分唯一还原二叉树过程与先序加后序单支形态歧义对比">
    <defs>
      <marker id="wz-w3-arr-8" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="14" width="430" height="254" rx="8"/>
    <rect class="fig-box-subtle" x="458" y="14" width="226" height="254" rx="8"/>
    <g class="fig-line" marker-end="url(#wz-w3-arr-8)">
      <path d="M 96 76 C 96 96, 178 96, 178 106"/>
      <line x1="230" y1="138" x2="230" y2="162"/>
    </g>
    <g class="fig-line">
      <line x1="230" y1="180" x2="168" y2="218"/>
      <line x1="230" y1="180" x2="292" y2="218"/>
      <line x1="168" y1="218" x2="140" y2="250"/>
      <line x1="168" y1="218" x2="196" y2="250"/>
      <line x1="292" y1="218" x2="266" y2="250"/>
      <line x1="528" y1="112" x2="500" y2="158"/>
      <line x1="614" y1="112" x2="642" y2="158"/>
    </g>
    <rect class="fig-box-accent" x="80" y="48" width="32" height="26" rx="4"/>
    <rect class="fig-box-blue" x="116" y="48" width="102" height="26" rx="4"/>
    <rect class="fig-box-green" x="222" y="48" width="68" height="26" rx="4"/>
    <rect class="fig-box-blue" x="80" y="108" width="102" height="26" rx="4"/>
    <rect class="fig-box-accent" x="186" y="108" width="32" height="26" rx="4"/>
    <rect class="fig-box-green" x="222" y="108" width="68" height="26" rx="4"/>
    <circle class="fig-box-accent" cx="230" cy="180" r="13"/>
    <circle class="fig-box-blue" cx="168" cy="218" r="13"/>
    <circle class="fig-box-green" cx="292" cy="218" r="13"/>
    <circle class="fig-box-blue" cx="140" cy="250" r="11"/>
    <circle class="fig-box-blue" cx="196" cy="250" r="11"/>
    <circle class="fig-box-green" cx="266" cy="250" r="11"/>
    <circle class="fig-box-accent" cx="528" cy="112" r="14"/>
    <circle class="fig-box-blue" cx="500" cy="158" r="14"/>
    <circle class="fig-box-accent" cx="614" cy="112" r="14"/>
    <circle class="fig-box-orange" cx="642" cy="158" r="14"/>
    <rect class="fig-box-red" x="472" y="192" width="198" height="62" rx="6"/>
    <g font-size="11.5">
      <text class="fig-title" x="231" y="34" text-anchor="middle">先序 + 中序（或后序 + 中序）唯一建树切分</text>
      <text class="fig-label" x="30" y="66">先序</text>
      <text class="fig-label" x="30" y="126">中序</text>
      <text class="fig-accent" x="302" y="66">① 先序首结点 A 定根</text>
      <text class="fig-blue" x="302" y="118">② 中序搜 A 切左右</text>
      <text class="fig-muted" x="302" y="135" font-size="10.5">左 m=3 个，右 r=2 个</text>
      <text class="fig-muted" x="320" y="218" font-size="10.5">③ 子树递归切分：</text>
      <text class="fig-blue" x="320" y="236" font-size="10.5">左：先 BDE / 中 DBE</text>
      <text class="fig-green" x="320" y="253" font-size="10.5">右：先 CF / 中 FC</text>
      <text class="fig-title" x="571" y="34" text-anchor="middle">先序 + 后序为何不能？</text>
      <text class="fig-muted" x="571" y="58" text-anchor="middle" font-size="11">已知先序 A B，后序 B A</text>
      <text class="fig-muted" x="571" y="76" text-anchor="middle" font-size="11">两棵不同二叉树完全同序列：</text>
    </g>
    <g font-size="11.5" text-anchor="middle">
      <text class="fig-accent" x="96" y="65">A</text>
      <text class="fig-blue" x="167" y="65">B   D   E</text>
      <text class="fig-green" x="256" y="65">C   F</text>
      <text class="fig-blue" x="131" y="125">D   B   E</text>
      <text class="fig-accent" x="202" y="125">A</text>
      <text class="fig-green" x="256" y="125">F   C</text>
      <text class="fig-accent" x="230" y="184">A</text>
      <text class="fig-blue" x="168" y="222">B</text><text class="fig-green" x="292" y="222">C</text>
      <text class="fig-blue" x="140" y="254" font-size="10.5">D</text><text class="fig-blue" x="196" y="254" font-size="10.5">E</text>
      <text class="fig-green" x="266" y="254" font-size="10.5">F</text>
      <text class="fig-accent" x="528" y="116">A</text><text class="fig-blue" x="500" y="162">B</text>
      <text class="fig-blue" x="514" y="182" font-size="10.5">左孩子</text>
      <text class="fig-accent" x="614" y="116">A</text><text class="fig-orange" x="642" y="162">B</text>
      <text class="fig-orange" x="628" y="182" font-size="10.5">右孩子</text>
      <text class="fig-red" x="571" y="213" font-size="11">存在度为 1 的结点时</text>
      <text class="fig-red" x="571" y="230" font-size="11">缺少中序，无法分清左右！</text>
      <text class="fig-muted" x="571" y="246" font-size="10">（仅当 n₁=0 即正则二叉树时唯一）</text>
    </g>
  </svg>
  <figcaption>遍历序列建树：先/后序定根 + 中序分左右可唯一还原；先序 + 后序遇单孩子结点必生左右歧义</figcaption>
</figure>

### 中序遍历的非递归算法

中序要求“左子树访问完再访问根”，所以遇到根不能立即访问，需要先存起来，等左子树回来后再取——**后存先取**，用**栈**实现。

步骤：指针 `p` 从根出发；`p` 不空则入栈并一路向左；`p` 为空则出栈访问该结点，然后 `p` 转向其右孩子。循环直到 `p` 为空且栈空。

```c
void InOrderTraverse(BiTree T) {
    InitStack(S);
    BiTNode *p = T, *q;
    while (p || !StackEmpty(S)) {
        if (p) {                 // 根先不入输出，入栈后深入左子树
            Push(S, p);
            p = p->lchild;
        } else {                 // 左子树为空，弹出栈顶即"最左未访问"的根
            Pop(S, q);
            visit(q);
            p = q->rchild;       // 转向右子树
        }
    }
}
```

时间复杂度 $O(n)$，空间为栈，最坏 $O(n)$。

> **注意**：循环条件必须是 `p || !StackEmpty(S)`。只判 `p` 会在左子树走空时提前结束，漏掉栈中尚未访问的根及其右子树。

### 层次遍历

按层次从上到下、每层从左到右访问每个结点一次。与先/中/后序不同，它不按子树递归，而是按“层”推进。

实现用**队列**：根入队；循环出队一个结点并访问，同时把其左孩子、右孩子（若存在）依次入队；队空则结束。队列的先进先出正好保证上层结点先于下层、左孩子先于右孩子被访问。

```c
void LevelOrder(BiTree T) {
    InitQueue(Q);
    if (T) EnQueue(Q, T);
    while (!QueueEmpty(Q)) {
        DeQueue(Q, p);
        visit(p);
        if (p->lchild) EnQueue(Q, p->lchild);
        if (p->rchild) EnQueue(Q, p->rchild);
    }
}
```

队列可用顺序循环队列（`front` 指向队头元素，`rear` 指向队尾元素的下一位置，少用一个元素空间判满）。时间 $O(n)$，空间为队列，最坏 $O(n)$（最后一层结点数可达 $\lceil n/2 \rceil$）。

<figure class="cpd-figure not-content" id="wz-w3-fig-9">
  <svg viewBox="0 0 700 284" role="img" aria-label="中序非递归遍历显式栈 S 轨迹与层次遍历循环队列 Q 状态推进对照">
    <defs>
      <marker id="wz-w3-arr-9" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="14" width="330" height="256" rx="8"/>
    <rect class="fig-box-subtle" x="356" y="14" width="328" height="256" rx="8"/>
    <g class="fig-line">
      <line x1="92" y1="62" x2="58" y2="108"/><line x1="92" y1="62" x2="126" y2="108"/>
      <line x1="58" y1="108" x2="40" y2="154"/><line x1="58" y1="108" x2="80" y2="154"/>
    </g>
    <g class="fig-line" marker-end="url(#wz-w3-arr-9)">
      <line x1="518" y1="74" x2="518" y2="90"/>
      <line x1="518" y1="120" x2="518" y2="136"/>
      <line x1="518" y1="166" x2="518" y2="182"/>
    </g>
    <circle class="fig-box-accent" cx="92" cy="62" r="13"/>
    <circle class="fig-box-blue" cx="58" cy="108" r="13"/>
    <circle class="fig-box-green" cx="126" cy="108" r="13"/>
    <circle class="fig-box-blue" cx="40" cy="154" r="12"/>
    <circle class="fig-box-blue" cx="80" cy="154" r="12"/>
    <rect class="fig-box" x="158" y="48" width="64" height="122" rx="4"/>
    <rect class="fig-box-accent" x="164" y="136" width="52" height="26" rx="3"/>
    <rect class="fig-box-blue" x="164" y="106" width="52" height="26" rx="3"/>
    <rect class="fig-box-blue" x="164" y="76" width="52" height="26" rx="3"/>
    <rect class="fig-box-orange" x="28" y="210" width="306" height="46" rx="6"/>
    <rect class="fig-box" x="370" y="48" width="298" height="26" rx="4"/>
    <rect class="fig-box" x="370" y="94" width="298" height="26" rx="4"/>
    <rect class="fig-box" x="370" y="140" width="298" height="26" rx="4"/>
    <rect class="fig-box" x="370" y="186" width="298" height="26" rx="4"/>
    <rect class="fig-box-purple" x="370" y="222" width="298" height="34" rx="6"/>
    <g font-size="11.5" text-anchor="middle">
      <text class="fig-title" x="181" y="34">中序非递归：栈 S 后进先出</text>
      <text class="fig-accent" x="92" y="66">A</text>
      <text class="fig-blue" x="58" y="112">B</text><text class="fig-green" x="126" y="112">C</text>
      <text class="fig-blue" x="40" y="158" font-size="11">D</text><text class="fig-blue" x="80" y="158" font-size="11">E</text>
      <text class="fig-purple" x="190" y="66" font-size="10.5">栈顶 top</text>
      <text class="fig-blue" x="190" y="93">D</text>
      <text class="fig-blue" x="190" y="123">B</text>
      <text class="fig-accent" x="190" y="153">A</text>
      <text class="fig-title" x="520" y="34">层次遍历：队列 Q 先进先出</text>
    </g>
    <g font-size="10.5">
      <text class="fig-label" x="230" y="70">① 一路向左入栈</text>
      <text class="fig-muted" x="230" y="88">Push: A→B→D</text>
      <text class="fig-label" x="230" y="114">② 走空则弹栈访问</text>
      <text class="fig-muted" x="230" y="132">Pop 访 D,B → 转 E</text>
      <text class="fig-green" x="230" y="158">输出：D B E A C</text>
      <text class="fig-orange" x="38" y="228" font-size="11">易错：循环判据必为 while (p || !StackEmpty(S))</text>
      <text class="fig-muted" x="38" y="246">当 B 的右子树 E 访完后 p==NULL，全靠栈非空续访根 A！</text>
      <text class="fig-accent" x="380" y="65">初态入队：[ A ]</text>
      <text class="fig-muted" x="506" y="65">（front → A，rear 指向尾后）</text>
      <text class="fig-blue" x="380" y="111">出 A 入左 B 右 C：[ B, C ]</text>
      <text class="fig-green" x="556" y="111">已访：A</text>
      <text class="fig-blue" x="380" y="157">出 B 入左 D 右 E：[ C, D, E ]</text>
      <text class="fig-green" x="556" y="157">已访：A B</text>
      <text class="fig-blue" x="380" y="203">依次出 C, D, E 队空：[ ∅ ]</text>
      <text class="fig-green" x="546" y="203">终态：A B C D E</text>
      <text class="fig-purple" x="382" y="243" font-size="11">队列峰值容量由最宽层决定，满树末层可达 ⌈n/2⌉ = O(n)</text>
    </g>
  </svg>
  <figcaption>非递归遍历双器对照：中序用栈暂存“待回访的根”，层序用队列保证“上层先于下层、左孩先于右孩”</figcaption>
</figure>

> **交互演示**：[二叉树递归/非递归遍历与层序遍历](/lab/chapter-6/#lab-traverse_pre)

### 遍历算法的应用

遍历框架中把“输出结点值”换成其他操作，即可完成各类运算，全部为递归 $O(n)$。

**1. 按先序序列建树**：仅凭先序序列不能唯一确定二叉树，必须把空子树也写进序列，用特殊符号（如 `#`）表示空。

```c
void CreateBiTree(BiTree *T) {
    scanf("%c", &ch);
    if (ch == '#') *T = NULL;              // 空子树
    else {
        *T = (BiTNode *)malloc(sizeof(BiTNode));
        (*T)->data = ch;                   // 先建根
        CreateBiTree(&((*T)->lchild));     // 再建左子树
        CreateBiTree(&((*T)->rchild));     // 最后建右子树
    }
}
```

**2. 复制二叉树**：先序思想——先复制根，再递归复制左、右子树。

```c
void Copy(BiTree T, BiTree *NewT) {
    if (!T) { *NewT = NULL; return; }
    *NewT = (BiTNode *)malloc(sizeof(BiTNode));
    (*NewT)->data = T->data;
    Copy(T->lchild, &((*NewT)->lchild));
    Copy(T->rchild, &((*NewT)->rchild));
}
```

**3. 求结点总数**：空树为 0；否则左子树结点数 + 右子树结点数 + 1（根）。

```c
int NodeCount(BiTree T) {
    if (!T) return 0;
    return NodeCount(T->lchild) + NodeCount(T->rchild) + 1;
}
```

**4. 求叶子结点数**：空树为 0；左右孩子都空则为 1 个叶子；否则为左右子树叶子数之和（根不是叶子，**不加 1**）。

```c
int LeafCount(BiTree T) {
    if (!T) return 0;
    if (!T->lchild && !T->rchild) return 1;
    return LeafCount(T->lchild) + LeafCount(T->rchild);
}
```

**5. 求树的深度**：空树为 0；否则取左右子树深度的较大者再加 1（根这一层）。

```c
int Depth(BiTree T) {
    if (!T) return 0;
    int m = Depth(T->lchild), n = Depth(T->rchild);
    return (m > n ? m : n) + 1;
}
```

> **★考点**：五个算法骨架相同（判空出口 + 递归左右 + 合并），差异只在“根何时处理、合并时是否 +1”。求结点数要加根，求叶子数不加根但要多一个“左右皆空”的判断。

### 线索二叉树

**为什么需要线索**：二叉链表找左右孩子很方便，但要找**某种遍历序列下的前驱和后继**很麻烦——要么重新遍历一遍（浪费时间），要么给每个结点再加两个指针域（浪费空间）。而 $n$ 个结点的二叉链表有 $2n$ 个指针域，只有 $n-1$ 个用于指向孩子，剩下 **$n+1$ 个空指针域**。

把空着的左孩子指针域用来存放该结点在某种遍历序列中的**前驱**、空着的右孩子指针域存放**后继**，这种指向前驱/后继的指针称为**线索**，加上线索的二叉树称为**线索二叉树**（thread binary tree），改造过程称为**线索化**。

**结点结构**：在二叉链表上增加两个标志域。

| lchild | ltag | data | rtag | rchild |
|---|---|---|---|---|
| 左孩子或前驱 | 0/1 | 数据元素 | 0/1 | 右孩子或后继 |

```c
typedef struct BiThrNode {
    TElemType data;
    struct BiThrNode *lchild, *rchild;
    int ltag, rtag;              // 0: 指向孩子   1: 指向前驱/后继
} BiThrNode, *BiThrTree;
```

- `ltag = 0`：`lchild` 指向左孩子；`ltag = 1`：`lchild` 指向**前驱**。
- `rtag = 0`：`rchild` 指向右孩子；`rtag = 1`：`rchild` 指向**后继**。

**三种线索树**：线索记录的是“哪一种遍历次序”下的前驱/后继，因此有**先序线索树、中序线索树、后序线索树**之分；同一棵二叉树按不同次序线索化，得到的线索指针不同，但结点数和树的形态不变。

线索化的建立思路（以中序为例，用指针 `pre` 记住刚访问过的结点）：

1. 按中序次序递归遍历，`pre` 初值为空；
2. 访问结点 `p` 时，若 `p->lchild` 为空，则令 `ltag = 1`、`lchild = pre`；
3. 若 `pre` 非空且 `pre->rchild` 为空，则令 `pre->rtag = 1`、`pre->rchild = p`；
4. 令 `pre = p`，继续遍历右子树。

先序、后序线索化只需把“访问结点”的时机换成对应的先序/后序位置；递归深入子树时必须按标记判断（`ltag == 0` 才是左孩子），否则会沿新造的线索走进前驱。

**中序线索链表上找前驱/后继与遍历**：

- 中序**第一个结点**：从根出发沿左孩子一路走到最左下，`while (p->ltag == 0) p = p->lchild;`
- **后继**：若 `p->rtag == 1`，`p->rchild` 就是后继；否则后继是**右子树中最左下的结点**。
- **前驱**：若 `p->ltag == 1`，`p->lchild` 就是前驱；否则前驱是**左子树中最右下的结点**。
- **遍历**：`p = First(T); while (p) { visit(p); p = Successor(p); }`

先序线索树找**后继**容易（有左孩子即左孩子，否则右孩子），找前驱需要双亲信息；后序线索树正好相反，找**前驱**容易，找后继需要双亲。因此常配合**三叉链表**（增加 `parent` 指针）或加头结点使用。

**头结点**：为避免第一个结点的左线索和最后一个结点的右线索悬空，仿照循环链表增设一个头结点（五个成员，`data` 不用）：

- `ltag = 0`，`lchild` 指向根结点；
- `rtag = 1`，`rchild` 指向遍历序列中的**最后一个结点**；
- 序列第一个结点的左线索、最后一个结点的右线索都指向头结点。

这样从任一结点出发都能顺着线索绕回头结点，再访问其他结点，操作类似单循环链表。

> **★考点**：中序线索树中“右线索指向后继”只在 `rtag == 1` 时成立；`rtag == 0` 时必须进入右子树再找最左下结点。
>
> **注意**：有头结点时，遍历的终止条件是“`p` 回到头结点”而不是 `p == NULL`；无头结点时，最后一个结点的右线索为空，遍历到 `p == NULL` 结束。线索化只改空指针域和标志，不新增结点、不改变树的形态，中序序列与原二叉树完全相同。

<figure class="cpd-figure not-content" id="wz-w3-fig-10">
  <svg viewBox="0 0 700 302" role="img" aria-label="带头结点的中序线索二叉树存储结构及 ltag、rtag 前驱后继查找规则">
    <defs>
      <marker id="wz-w3-arr-10s" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="14" width="414" height="274" rx="8"/>
    <rect class="fig-box-subtle" x="442" y="14" width="242" height="274" rx="8"/>
    <g class="fig-line" marker-end="url(#wz-w3-arr-10s)">
      <line x1="194" y1="54" x2="212" y2="86"/>
      <line x1="210" y1="108" x2="144" y2="152"/>
      <line x1="246" y1="108" x2="312" y2="152"/>
      <line x1="118" y1="174" x2="80" y2="220"/>
      <line x1="154" y1="174" x2="192" y2="220"/>
    </g>
    <g class="fig-line-dashed" stroke="var(--sl-color-blue)" marker-end="url(#wz-w3-arr-10s)">
      <path d="M 54 232 C 26 218, 36 52, 166 44"/>
      <path d="M 178 232 C 156 226, 146 198, 138 178"/>
      <path d="M 302 164 C 276 154, 256 128, 236 112"/>
    </g>
    <g class="fig-line-dashed" stroke="var(--sl-color-orange)" marker-end="url(#wz-w3-arr-10s)">
      <path d="M 94 232 C 114 226, 124 198, 132 178"/>
      <path d="M 218 232 C 242 210, 234 146, 228 112"/>
      <path d="M 342 164 C 378 148, 362 46, 230 44"/>
      <path d="M 230 36 C 340 24, 388 116, 336 152"/>
    </g>
    <rect class="fig-box-purple" x="168" y="30" width="60" height="24" rx="4"/>
    <rect class="fig-box-accent" x="198" y="86" width="60" height="24" rx="4"/>
    <rect class="fig-box-blue" x="106" y="152" width="60" height="24" rx="4"/>
    <rect class="fig-box-green" x="292" y="152" width="60" height="24" rx="4"/>
    <rect class="fig-box" x="44" y="220" width="60" height="24" rx="4"/>
    <rect class="fig-box" x="168" y="220" width="60" height="24" rx="4"/>
    <rect class="fig-box" x="454" y="42" width="218" height="32" rx="4"/>
    <rect class="fig-box" x="454" y="84" width="218" height="62" rx="6"/>
    <rect class="fig-box" x="454" y="154" width="218" height="62" rx="6"/>
    <rect class="fig-box-orange" x="454" y="224" width="218" height="52" rx="6"/>
    <g font-size="10.5" text-anchor="middle">
      <text class="fig-purple" x="198" y="46">0 | H | 1</text>
      <text class="fig-accent" x="228" y="102">0 | A | 0</text>
      <text class="fig-blue" x="136" y="168">0 | B | 0</text>
      <text class="fig-green" x="322" y="168">1 | C | 1</text>
      <text class="fig-label" x="74" y="236">1 | D | 1</text>
      <text class="fig-label" x="198" y="236">1 | E | 1</text>
      <text class="fig-muted" x="223" y="268" font-size="11">中序序列：D → B → E → A → C（蓝虚线=前驱，橙虚线=后继）</text>
      <text class="fig-title" x="563" y="33" font-size="11.5">中序线索查找核心法则</text>
      <text class="fig-label" x="563" y="62">lchild | ltag | data | rtag | rchild</text>
    </g>
    <g font-size="10.5">
      <text class="fig-orange" x="464" y="102">求中序后继 Next(p)：</text>
      <text class="fig-label" x="464" y="119">• rtag == 1：直接取 p-&gt;rchild（如 E→A）</text>
      <text class="fig-label" x="464" y="136">• rtag == 0：右子树最左下（如 A→C）</text>
      <text class="fig-blue" x="464" y="172">求中序前驱 Prior(p)：</text>
      <text class="fig-label" x="464" y="189">• ltag == 1：直接取 p-&gt;lchild（如 C→A）</text>
      <text class="fig-label" x="464" y="206">• ltag == 0：左子树最右下（如 A→E）</text>
      <text class="fig-orange" x="464" y="242">★ 难点对比（无双亲指针时）：</text>
      <text class="fig-muted" x="464" y="259">先序线索找前驱难；后序线索找后继难！</text>
    </g>
  </svg>
  <figcaption>带头结点 H 的中序线索二叉树：实线（tag=0）连孩子，虚线（tag=1）连前驱/后继，构成双向线索环</figcaption>
</figure>

> **交互演示**：[中序线索化](/lab/chapter-6/#lab-threading)

### 树的存储结构：双亲表示法

树是 $n$ 个节点的集合：$n=0$ 时为空树；$n>0$ 时由根节点和若干互不相交的子树构成，是递归定义。森林是 $m$ 棵互不相交的树的集合（$m\ge 0$）：树去掉根节点即成为森林，森林加一个根节点即成为树。

**双亲表示法**用一组连续空间（结构数组）存放树中节点，每个节点除数据元素外，再记录其双亲在数组中的下标。根节点没有双亲，其 `parent` 置为 $-1$。

```c
typedef struct {
    ElemType data;   // 数据元素
    int parent;      // 双亲在数组中的下标，根为 -1
} PTNode;

typedef struct {
    PTNode nodes[MAXSIZE];
    int r;           // 根节点的下标
    int n;           // 节点总数
} PTree;
```

以 10 个节点为例：`0:r` 为根；`1:a、2:b、3:c` 的双亲都是 0；`4:d、5:e` 的双亲是 1；`6:f` 的双亲是 3；`7:g、8:h、9:k` 的双亲都是 6。于是由 `parent` 一列即可还原整棵树。

<figure class="cpd-figure not-content" id="wz-fig-14">
  <svg viewBox="0 0 700 288" role="img" aria-label="树的双亲表示法：10 结点树形结构与 PTree 顺序数组下标及 parent 域对照">
    <rect class="fig-box-subtle" x="16" y="14" width="322" height="260" rx="8"/>
    <rect class="fig-box-subtle" x="350" y="14" width="334" height="260" rx="8"/>
    <g class="fig-line">
      <line x1="176" y1="54" x2="88" y2="110"/>
      <line x1="176" y1="54" x2="176" y2="110"/>
      <line x1="176" y1="54" x2="264" y2="110"/>
      <line x1="88" y1="110" x2="60" y2="166"/>
      <line x1="88" y1="110" x2="116" y2="166"/>
      <line x1="264" y1="110" x2="264" y2="166"/>
      <line x1="264" y1="166" x2="220" y2="222"/>
      <line x1="264" y1="166" x2="264" y2="222"/>
      <line x1="264" y1="166" x2="308" y2="222"/>
    </g>
    <circle class="fig-box-accent" cx="176" cy="54" r="14"/>
    <g class="fig-box-blue">
      <circle cx="88" cy="110" r="14"/><circle cx="176" cy="110" r="14"/><circle cx="264" cy="110" r="14"/>
    </g>
    <g class="fig-box-green">
      <circle cx="60" cy="166" r="14"/><circle cx="116" cy="166" r="14"/>
      <circle cx="220" cy="222" r="14"/><circle cx="264" cy="222" r="14"/><circle cx="308" cy="222" r="14"/>
    </g>
    <circle class="fig-box-blue" cx="264" cy="166" r="14"/>
    <rect class="fig-box" x="368" y="38" width="298" height="202" rx="4"/>
    <g class="fig-divider">
      <line x1="368" y1="58" x2="666" y2="58"/><line x1="368" y1="76" x2="666" y2="76"/>
      <line x1="368" y1="94" x2="666" y2="94"/><line x1="368" y1="112" x2="666" y2="112"/>
      <line x1="368" y1="130" x2="666" y2="130"/><line x1="368" y1="148" x2="666" y2="148"/>
      <line x1="368" y1="166" x2="666" y2="166"/><line x1="368" y1="184" x2="666" y2="184"/>
      <line x1="368" y1="202" x2="666" y2="202"/><line x1="368" y1="220" x2="666" y2="220"/>
      <line x1="454" y1="38" x2="454" y2="240"/><line x1="556" y1="38" x2="556" y2="240"/>
    </g>
    <g font-size="11.5" text-anchor="middle">
      <text class="fig-title" x="177" y="32">10 结点树（上标为数组下标）</text>
      <text class="fig-accent" x="176" y="58">r</text><text class="fig-muted" x="198" y="50" font-size="10">0</text>
      <text class="fig-blue" x="88" y="114">a</text><text class="fig-muted" x="67" y="106" font-size="10">1</text>
      <text class="fig-blue" x="176" y="114">b</text><text class="fig-muted" x="197" y="106" font-size="10">2</text>
      <text class="fig-blue" x="264" y="114">c</text><text class="fig-muted" x="285" y="106" font-size="10">3</text>
      <text class="fig-green" x="60" y="170">d</text><text class="fig-muted" x="39" y="162" font-size="10">4</text>
      <text class="fig-green" x="116" y="170">e</text><text class="fig-muted" x="137" y="162" font-size="10">5</text>
      <text class="fig-blue" x="264" y="170">f</text><text class="fig-muted" x="285" y="162" font-size="10">6</text>
      <text class="fig-green" x="220" y="226">g</text><text class="fig-muted" x="199" y="218" font-size="10">7</text>
      <text class="fig-green" x="264" y="226">h</text><text class="fig-muted" x="264" y="248" font-size="10">8</text>
      <text class="fig-green" x="308" y="226">k</text><text class="fig-muted" x="328" y="218" font-size="10">9</text>
      <text class="fig-muted" x="140" y="258" font-size="10.5">并查集（Union-Find）底层即双亲表示法</text>
      <text class="fig-title" x="517" y="28">PTree 结构数组（r=0, n=10）</text>
      <text class="fig-title" x="411" y="52" font-size="11">下标</text><text class="fig-title" x="505" y="52" font-size="11">data</text><text class="fig-title" x="611" y="52" font-size="11">parent</text>
      <text class="fig-muted" x="411" y="71">0</text><text class="fig-accent" x="505" y="71">r</text><text class="fig-orange" x="611" y="71">-1（根）</text>
      <text class="fig-muted" x="411" y="89">1</text><text class="fig-label" x="505" y="89">a</text><text class="fig-blue" x="611" y="89">0</text>
      <text class="fig-muted" x="411" y="107">2</text><text class="fig-label" x="505" y="107">b</text><text class="fig-blue" x="611" y="107">0</text>
      <text class="fig-muted" x="411" y="125">3</text><text class="fig-label" x="505" y="125">c</text><text class="fig-blue" x="611" y="125">0</text>
      <text class="fig-muted" x="411" y="143">4</text><text class="fig-label" x="505" y="143">d</text><text class="fig-blue" x="611" y="143">1</text>
      <text class="fig-muted" x="411" y="161">5</text><text class="fig-label" x="505" y="161">e</text><text class="fig-blue" x="611" y="161">1</text>
      <text class="fig-muted" x="411" y="179">6</text><text class="fig-label" x="505" y="179">f</text><text class="fig-blue" x="611" y="179">3</text>
      <text class="fig-muted" x="411" y="197">7</text><text class="fig-label" x="505" y="197">g</text><text class="fig-blue" x="611" y="197">6</text>
      <text class="fig-muted" x="411" y="215">8</text><text class="fig-label" x="505" y="215">h</text><text class="fig-blue" x="611" y="215">6</text>
      <text class="fig-muted" x="411" y="233">9</text><text class="fig-label" x="505" y="233">k</text><text class="fig-blue" x="611" y="233">6</text>
      <text class="fig-muted" x="517" y="258" font-size="10.5">求双亲 O(1)，求孩子需扫全表 O(n)</text>
    </g>
  </svg>
  <figcaption>树的双亲表示法：parent 域记录双亲下标（根置 -1，勿与哈夫曼树置 0 混淆），求根与并查集极快</figcaption>
</figure>

**特点**：找双亲只需读一个域，很容易；找孩子则要扫描整个数组，比较困难。若操作以“求双亲”为主，宜用这种结构。

> **注意**：双亲表示法用 `-1` 表示根无双亲；哈夫曼树的顺序存储用 `0` 表示“无”（根的 `parent`、叶子的 `lchild` 与 `rchild` 均为 0）。两者不要混淆。

### 树的存储结构：孩子链表

**孩子链表**把每个节点的孩子看成一个线性表，用单链表存储。$n$ 个节点就对应 $n$ 个孩子链表，叶子节点的链表为空表；所有链表的头指针再组成一个数组，以便按节点找到各自的孩子链。

- 孩子节点：`child` 存该孩子在表头数组中的下标，`next` 指向下一个孩子。
- 表头节点：`data` 存数据元素，`firstchild` 指向第一个孩子。

```c
typedef struct CSNode {
    int child;             // 孩子在表头数组中的下标
    struct CSNode *next;   // 下一个孩子
} CSNode, *CList;

typedef struct {
    ElemType data;
    CList firstchild;      // 指向第一个孩子
} CTNode;

CTNode nodes[MAXSIZE];     // 表头数组
```

若既要找孩子又要找双亲，可在表头节点中再加一个 `parent` 域，构成**带双亲的孩子链表**，以少量空间换取求双亲的方便。

| 存储结构 | 找双亲 | 找孩子 |
|---|---|---|
| 双亲表示法 | 容易，读 `parent` 即可 | 困难，需扫描全表 |
| 孩子链表 | 困难，需遍历所有链表查找 | 容易，顺链表即可 |
| 带双亲的孩子链表 | 容易 | 容易 |

### 树的存储结构：孩子兄弟表示法

**孩子兄弟表示法**又称**二叉链表表示法**（二叉树表示法）。每个节点仍是“一个数据域 + 两个指针域”，只是指针含义变为：

- `firstchild`：指向第一个孩子；
- `nextsibling`：指向下一个兄弟。

```c
typedef struct CSNode {
    ElemType data;
    struct CSNode *firstchild;    // 第一个孩子
    struct CSNode *nextsibling;   // 下一个兄弟
} CSNode, *CSTree;
```

其形式与二叉树的二叉链表完全一致，这正是树与二叉树能够相互转换的基础；口诀就是**左孩子右兄弟**。

**查找方法**：由 `firstchild` 找到长子，再沿长子（以及其他孩子）的 `nextsibling` 依次找到全部孩子；因此找孩子、找兄弟都容易，找双亲困难，必要时可再增加一个 `parent` 指针。

> **注意**：`nextsibling` 串起来的是同一双亲下的兄弟，不是堂兄弟；根节点没有兄弟，其 `nextsibling` 为空。

<figure class="cpd-figure not-content" id="wz-w3-fig-11">
  <svg viewBox="0 0 700 282" role="img" aria-label="树的孩子链表表示法与孩子兄弟二叉链表表示法（左孩子右兄弟）对比">
    <defs>
      <marker id="wz-w3-arr-11" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="14" width="332" height="254" rx="8"/>
    <rect class="fig-box-subtle" x="360" y="14" width="324" height="254" rx="8"/>
    <g class="fig-line" marker-end="url(#wz-w3-arr-11)">
      <line x1="126" y1="62" x2="152" y2="62"/><line x1="196" y1="62" x2="216" y2="62"/><line x1="260" y1="62" x2="280" y2="62"/>
      <line x1="126" y1="92" x2="152" y2="92"/><line x1="196" y1="92" x2="216" y2="92"/>
      <line x1="126" y1="152" x2="152" y2="152"/>
      <line x1="494" y1="74" x2="446" y2="114"/>
      <line x1="464" y1="126" x2="520" y2="126"/>
      <line x1="568" y1="126" x2="614" y2="126"/>
      <line x1="428" y1="138" x2="398" y2="178"/>
      <line x1="416" y1="190" x2="466" y2="190"/>
      <line x1="626" y1="138" x2="626" y2="178"/>
    </g>
    <rect class="fig-box" x="48" y="48" width="78" height="26" rx="3"/>
    <rect class="fig-box" x="48" y="78" width="78" height="26" rx="3"/>
    <rect class="fig-box" x="48" y="108" width="78" height="26" rx="3"/>
    <rect class="fig-box" x="48" y="138" width="78" height="26" rx="3"/>
    <rect class="fig-box" x="48" y="168" width="78" height="26" rx="3"/>
    <rect class="fig-box" x="48" y="198" width="78" height="26" rx="3"/>
    <g class="fig-box-blue">
      <rect x="152" y="50" width="44" height="24" rx="3"/><rect x="216" y="50" width="44" height="24" rx="3"/><rect x="280" y="50" width="48" height="24" rx="3"/>
      <rect x="152" y="80" width="44" height="24" rx="3"/><rect x="216" y="80" width="48" height="24" rx="3"/>
      <rect x="152" y="140" width="48" height="24" rx="3"/>
    </g>
    <rect class="fig-box-accent" x="482" y="50" width="54" height="24" rx="4"/>
    <rect class="fig-box-blue" x="416" y="114" width="48" height="24" rx="4"/>
    <rect class="fig-box-orange" x="520" y="114" width="48" height="24" rx="4"/>
    <rect class="fig-box-orange" x="614" y="114" width="48" height="24" rx="4"/>
    <rect class="fig-box-blue" x="368" y="178" width="48" height="24" rx="4"/>
    <rect class="fig-box-orange" x="466" y="178" width="48" height="24" rx="4"/>
    <rect class="fig-box-blue" x="602" y="178" width="48" height="24" rx="4"/>
    <rect class="fig-box" x="372" y="216" width="300" height="42" rx="6"/>
    <g font-size="10.5" text-anchor="middle">
      <text class="fig-title" x="182" y="34" font-size="11.5">孩子链表：表头数组 + 孩子单链表</text>
      <text class="fig-muted" x="34" y="65">0</text><text class="fig-accent" x="87" y="65">r  |  •</text>
      <text class="fig-muted" x="34" y="95">1</text><text class="fig-label" x="87" y="95">a  |  •</text>
      <text class="fig-muted" x="34" y="125">2</text><text class="fig-label" x="87" y="125">b  |  ∧</text>
      <text class="fig-muted" x="34" y="155">3</text><text class="fig-label" x="87" y="155">c  |  •</text>
      <text class="fig-muted" x="34" y="185">4</text><text class="fig-label" x="87" y="185">d  |  ∧</text>
      <text class="fig-muted" x="34" y="215">5</text><text class="fig-label" x="87" y="215">e  |  ∧</text>
      <text class="fig-blue" x="174" y="66">1|•</text><text class="fig-blue" x="238" y="66">2|•</text><text class="fig-blue" x="304" y="66">3|∧</text>
      <text class="fig-blue" x="174" y="96">4|•</text><text class="fig-blue" x="240" y="96">5|∧</text>
      <text class="fig-blue" x="176" y="156">6|∧</text>
      <text class="fig-muted" x="182" y="250" font-size="11">找孩子顺链即得；表头加 parent 域即“带双亲的孩子链表”</text>
      <text class="fig-title" x="522" y="34" font-size="11.5">孩子兄弟表示法（CSNode 左孩右兄）</text>
      <text class="fig-accent" x="509" y="66">• | r | ∧</text>
      <text class="fig-blue" x="440" y="130">a</text><text class="fig-orange" x="544" y="130">b</text><text class="fig-orange" x="638" y="130">c</text>
      <text class="fig-blue" x="392" y="194">d</text><text class="fig-orange" x="490" y="194">e</text><text class="fig-blue" x="626" y="194">f</text>
    </g>
    <g font-size="10.5">
      <text class="fig-blue" x="382" y="233">• 左指针 firstchild：向下一层指向第一个孩子（长子）</text>
      <text class="fig-orange" x="382" y="250">• 右指针 nextsibling：横向串联同双亲兄弟（根右必为 ∧）</text>
    </g>
  </svg>
  <figcaption>孩子链表与孩子兄弟表示法对比：CSNode 以“左孩子、右兄弟”将任意树同构映射为二叉链表</figcaption>
</figure>

### 树转换为二叉树

树与二叉树都可以用二叉链表存储。同一个二叉链表，按“左孩子、右孩子”解释就是二叉树，按“第一个孩子、下一个兄弟”解释就是树。由于树的二叉链表（孩子兄弟）表示是唯一的，所以**一棵树唯一对应一棵二叉树**，反之亦然。实际转换不必真的写出链表，按下面三步做即可。

1. **加线**：在所有相邻兄弟节点之间加一条连线。
2. **抹线**：对每个节点，只保留它与第一个孩子（长子）的连线，抹去它与其余孩子的连线。
3. **旋转**：以根节点为轴，把各节点顺时针旋转约 $45^\circ$，使层次分明。

口诀：**兄弟相连留长子**。

转换所得二叉树的**根节点没有右子树**，因为根没有兄弟，`nextsibling` 为空。

> **注意**：抹线抹的是“双亲与非长子孩子”的连线，不是兄弟之间的连线；加线只加在亲兄弟之间。

### 二叉树转换为树

把上述过程反过来，口诀为：**左孩右右连双亲，去掉原来右孩线**。

1. 若节点 $x$ 是其双亲的左孩子，则把 $x$ 的右孩子、右孩子的右孩子……即沿右分支一直向下的所有节点，都与 $x$ 的双亲相连。
2. 抹去原来双亲与这些右孩子之间的连线（加了几条就抹几条）。
3. 调整层次，把 $45^\circ$ 的斜线拉平，使同一双亲的孩子处于同一层。

转换后，同一双亲的所有孩子位于同一层，恢复为普通的树。

> **注意**：只有“左孩子”才触发连线，沿的是右分支；若二叉树的根有右子树，则它对应的不是一棵树，而是森林。

### 森林与二叉树的相互转换

**森林转换为二叉树**（口诀：**树变二叉根相连**）：

1. 对森林中每一棵树，按“兄弟相连留长子”分别转换成二叉树；
2. 把各棵二叉树的根节点依次相连，后一棵树的根作为前一棵树根的右孩子；
3. 以第一棵树的根作为整棵二叉树的根，顺时针旋转 $45^\circ$。

**二叉树转换为森林**（口诀：**去掉全部右孩线，孤立二叉再还原**）：

1. 抹去根节点与其右孩子、右孩子的右孩子……即全部右分支上的连线，得到若干棵孤立的二叉树；
2. 对每棵孤立的二叉树，按“左孩右右连双亲，去掉原来右孩线”还原成树。

由此可得判定：**二叉树能转换成一棵树，当且仅当根节点没有右子树**；根有右子树时，转换结果是森林。

> **交互演示**：[树/森林 ↔ 二叉树相互转换](/lab/chapter-6/#lab-forestConvert)

### 树与森林的遍历

树的遍历只有三种，没有中序：一个节点可以有多个子树，把“根”放在中间无法定义。

| 遍历 | 规则 |
|---|---|
| 先根遍历 | 访问根节点，再依次先根遍历各棵子树 |
| 后根遍历 | 依次后根遍历各棵子树，最后访问根节点 |
| 层次遍历 | 从上到下、从左到右依次访问每个节点 |

森林的遍历把森林看成三部分：① 第一棵树的根；② 第一棵树的子树森林；③ 其余树构成的森林。

| 遍历 | 规则 | 等价说法 |
|---|---|---|
| 先序遍历 | ①→②→③：访问第一棵树的根，先序遍历其子树森林，再先序遍历其余树构成的森林 | 依次对每棵树做先根遍历 |
| 中序遍历 | ②→①→③：中序遍历第一棵树的子树森林，访问第一棵树的根，再中序遍历其余树构成的森林 | 依次对每棵树做后根遍历 |

对应关系：树的先根遍历对应二叉树的先序遍历，树的后根遍历对应二叉树的中序遍历；森林的先序、中序分别对应其二叉树的先序、中序。

例：树 $a(b,\ c(d),\ e)$ 的三个序列为——先根 `a b c d e`，后根 `b d c e a`，层次 `a b c e d`。

> **注意**：森林的“中序”其实是逐棵树做后根遍历，不要按二叉树的“左—根—右”去套。

<figure class="cpd-figure not-content" id="wz-w3-fig-12">
  <svg viewBox="0 0 700 296" role="img" aria-label="树转换为二叉树的三步口诀过程与森林转换二叉树及遍历对应法则">
    <defs>
      <marker id="wz-w3-arr-12f" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="14" width="668" height="128" rx="8"/>
    <rect class="fig-box-subtle" x="16" y="152" width="668" height="130" rx="8"/>
    <g class="fig-line">
      <line x1="94" y1="54" x2="54" y2="98"/><line x1="94" y1="54" x2="94" y2="98"/><line x1="94" y1="54" x2="134" y2="98"/>
      <line x1="296" y1="54" x2="256" y2="98"/>
      <line x1="510" y1="48" x2="478" y2="78"/><line x1="478" y1="78" x2="510" y2="104"/><line x1="510" y1="104" x2="542" y2="128"/>
      <line x1="68" y1="192" x2="48" y2="232"/><line x1="68" y1="192" x2="88" y2="232"/>
      <line x1="146" y1="192" x2="146" y2="232"/>
      <line x1="336" y1="184" x2="306" y2="218"/><line x1="306" y1="218" x2="334" y2="250"/>
      <line x1="388" y1="210" x2="362" y2="244"/>
    </g>
    <g class="fig-line-dashed">
      <line x1="296" y1="54" x2="296" y2="98" stroke="var(--sl-color-red)"/>
      <line x1="296" y1="54" x2="336" y2="98" stroke="var(--sl-color-red)"/>
    </g>
    <g class="fig-line" stroke="var(--sl-color-orange)">
      <line x1="256" y1="98" x2="296" y2="98"/><line x1="296" y1="98" x2="336" y2="98"/>
      <line x1="336" y1="184" x2="388" y2="210"/><line x1="388" y1="210" x2="440" y2="236"/>
    </g>
    <g class="fig-line" marker-end="url(#wz-w3-arr-12f)">
      <line x1="168" y1="78" x2="218" y2="78"/>
      <line x1="372" y1="78" x2="424" y2="78"/>
      <line x1="234" y1="216" x2="278" y2="216"/>
    </g>
    <circle class="fig-box-accent" cx="94" cy="54" r="12"/>
    <g class="fig-box-blue">
      <circle cx="54" cy="98" r="12"/><circle cx="94" cy="98" r="12"/><circle cx="134" cy="98" r="12"/>
    </g>
    <circle class="fig-box-accent" cx="296" cy="54" r="12"/>
    <circle class="fig-box-blue" cx="256" cy="98" r="12"/>
    <circle class="fig-box-orange" cx="296" cy="98" r="12"/>
    <circle class="fig-box-orange" cx="336" cy="98" r="12"/>
    <circle class="fig-box-accent" cx="510" cy="48" r="11"/>
    <circle class="fig-box-blue" cx="478" cy="78" r="11"/>
    <circle class="fig-box-orange" cx="510" cy="104" r="11"/>
    <circle class="fig-box-orange" cx="542" cy="128" r="11"/>
    <circle class="fig-box-accent" cx="68" cy="192" r="11"/>
    <circle class="fig-box-blue" cx="48" cy="232" r="11"/><circle class="fig-box-blue" cx="88" cy="232" r="11"/>
    <circle class="fig-box-accent" cx="146" cy="192" r="11"/><circle class="fig-box-blue" cx="146" cy="232" r="11"/>
    <circle class="fig-box-accent" cx="206" cy="192" r="11"/>
    <circle class="fig-box-accent" cx="336" cy="184" r="11"/>
    <circle class="fig-box-blue" cx="306" cy="218" r="11"/><circle class="fig-box-orange" cx="334" cy="250" r="11"/>
    <circle class="fig-box-accent" cx="388" cy="210" r="11"/><circle class="fig-box-blue" cx="362" cy="244" r="11"/>
    <circle class="fig-box-accent" cx="440" cy="236" r="11"/>
    <rect class="fig-box" x="476" y="176" width="194" height="94" rx="6"/>
    <g font-size="11" text-anchor="middle">
      <text class="fig-title" x="350" y="31" font-size="11.5">树 ↔ 二叉树三步法：“兄弟相连留长子，顺时针转 45°”（转换后根必无右子树！）</text>
      <text class="fig-accent" x="94" y="58">A</text>
      <text class="fig-blue" x="54" y="102">B</text><text class="fig-blue" x="94" y="102">C</text><text class="fig-blue" x="134" y="102">D</text>
      <text class="fig-muted" x="94" y="128" font-size="10">原树 A(B, C, D)</text>
      <text class="fig-muted" x="193" y="70" font-size="10">①加线</text><text class="fig-red" x="193" y="92" font-size="10">②抹线</text>
      <text class="fig-accent" x="296" y="58">A</text>
      <text class="fig-blue" x="256" y="102">B</text><text class="fig-orange" x="296" y="102">C</text><text class="fig-orange" x="336" y="102">D</text>
      <text class="fig-muted" x="296" y="128" font-size="10">只留长子 B，抹红虚线</text>
      <text class="fig-muted" x="398" y="70" font-size="10">③旋转</text>
      <text class="fig-accent" x="510" y="52" font-size="10">A</text>
      <text class="fig-blue" x="478" y="82" font-size="10">B</text>
      <text class="fig-orange" x="510" y="108" font-size="10">C</text>
      <text class="fig-orange" x="542" y="132" font-size="10">D</text>
      <text class="fig-green" x="608" y="68" font-size="10.5">A 无右子树</text>
      <text class="fig-muted" x="608" y="86" font-size="10">（根无兄弟）</text>
      <text class="fig-title" x="242" y="169" font-size="11.5">森林 F = (T₁, T₂, T₃) ↔ 二叉树：“树变二叉根相连”</text>
      <text class="fig-accent" x="68" y="196" font-size="10">A</text>
      <text class="fig-blue" x="48" y="236" font-size="10">B</text><text class="fig-blue" x="88" y="236" font-size="10">C</text>
      <text class="fig-accent" x="146" y="196" font-size="10">D</text><text class="fig-blue" x="146" y="236" font-size="10">E</text>
      <text class="fig-accent" x="206" y="196" font-size="10">F</text>
      <text class="fig-muted" x="136" y="268" font-size="10">三棵互不相交的树</text>
      <text class="fig-accent" x="336" y="188" font-size="10">A</text>
      <text class="fig-blue" x="306" y="222" font-size="10">B</text><text class="fig-orange" x="334" y="254" font-size="10">C</text>
      <text class="fig-accent" x="388" y="214" font-size="10">D</text><text class="fig-blue" x="362" y="248" font-size="10">E</text>
      <text class="fig-accent" x="440" y="240" font-size="10">F</text>
      <text class="fig-orange" x="380" y="272" font-size="10">各树根 A→D→F 沿右斜线相连</text>
    </g>
    <g font-size="10.5">
      <text class="fig-title" x="573" y="194" text-anchor="middle" font-size="11">★ 408 遍历黄金对应表</text>
      <text class="fig-blue" x="486" y="214">树先根  ⇔  对应二叉树先序</text>
      <text class="fig-orange" x="486" y="232">树后根  ⇔  对应二叉树中序！</text>
      <text class="fig-green" x="486" y="250">森林先序 ⇔ 二叉先序</text>
      <text class="fig-purple" x="486" y="264">森林中序(=逐棵后根) ⇔ 二叉中序</text>
    </g>
  </svg>
  <figcaption>树/森林与二叉树的同构转换及遍历对应：注意树的“后根遍历”严格对应转换后二叉树的“中序遍历”</figcaption>
</figure>

### 哈夫曼树的基本概念

**引子**：把百分制成绩转成五分制，可用 if-else 嵌套，其判断过程可画成一棵**判定树**。设成绩分布为 $<60:5\%$、$60\sim69:15\%$、$70\sim79:40\%$、$80\sim89:30\%$、$\ge90:10\%$。

按 `<60 → <70 → <80 → <90` 的顺序判断，平均比较次数为

$$
0.05\times1+0.15\times2+0.40\times3+0.30\times4+0.10\times4=3.15
$$

若先判 `<80`，左侧再判 `<70`、`<60`，右侧判 `<90`，则

$$
0.20\times3+0.80\times2=2.2
$$

比较次数减少约 $30\%$。同一批数据，仅改变判断顺序就改变了效率，效率最高者即“最优判定树”。

基本术语：

- **路径**：树中从一个节点到另一个节点所经过的分支；分支个数称为**路径长度**。
- **树的路径长度**：从根节点到每个节点的路径长度之和（根到自身为 0）。节点数相同的二叉树，路径长度可以不同；**完全二叉树的路径长度最短**，但路径长度最短的不一定是完全二叉树（充分不必要）。
- **权**：给节点赋予的、具有某种含义的值，如该字符出现的频率或比例。
- **节点的带权路径长度**：从根到该节点的路径长度乘以该节点的权。
- **树的带权路径长度**：所有**叶子节点**的带权路径长度之和，记作

$$
WPL=\sum_{i=1}^{n} w_i l_i
$$

其中 $w_i$ 为第 $i$ 个叶子的权，$l_i$ 为根到该叶子的路径长度。

**哈夫曼树**：$WPL$ 最小的二叉树，又称**最优二叉树**；比较须在同一度数下进行（都讨论二叉树，或都讨论三叉树）。该构造方法由哈夫曼于 1952 年提出，故称哈夫曼树、哈夫曼算法。

以权值 $7,5,2,4$ 的四个叶子构造二叉树：

| 形态 | 各叶子路径长度 | $WPL$ |
|---|---|---|
| 满二叉树 | $2,2,2,2$ | $36$ |
| 一般形态 | $3,3,1,2$ | $46$ |
| 最优形态 | $1,2,3,3$ | $35$ |
| 另一最优形态 | $1,2,3,3$ | $35$ |

可见满二叉树不一定是哈夫曼树；哈夫曼树**不唯一**，但 $WPL$ 相同。其特点是：**权越大的叶子离根越近**，权越小离根越远。

### 哈夫曼树的构造

采用贪心策略：每次从当前森林中选权值最小的两棵树合并，让权小的先沉下去，权大的留到最后、离根更近。

构造口诀四句：

1. **构造森林全是根**：用 $n$ 个权值各造一棵只有一个根节点的二叉树，组成森林。
2. **选用两小造新树**：选根节点权值最小的两棵，一棵作左子树、一棵作右子树，新根的权为二者之和。
3. **删除两小添新人**：从森林中删去这两棵树，把新树加入森林。
4. **重复二三剩单根**：反复执行 2、3，直到森林中只剩一棵树，即为哈夫曼树。

以 $7,5,2,4$ 为例：

| 步骤 | 森林中的树（根权） | 合并 |
|---|---|---|
| 初始 | $\{7\},\{5\},\{2\},\{4\}$ | — |
| 1 | $\{7\},\{5\},\{6\}$ | $2+4=6$ |
| 2 | $\{7\},\{11\}$ | $5+6=11$ |
| 3 | $\{18\}$ | $7+11=18$ |

其 $WPL=7\times1+5\times2+2\times3+4\times3=35$，达到最优。

> **注意**：每次必须在“当前森林的所有根”中选两个最小者，已合并过的节点有双亲、不再是根，不能再次参选；左右子树的次序可交换，因此构造结果不唯一。

### 哈夫曼树的特点与顺序存储

设叶子数为 $n$。$n$ 棵单节点树要合并 $n-1$ 次才剩一棵，每次合并新增一个节点，故：

- 新增的 $n-1$ 个节点都有左右孩子，度为 2；
- 原有 $n$ 个节点度为 0；
- 哈夫曼树中**只有度为 0 和度为 2 的节点，没有度为 1 的节点**；
- 总节点数为 $n+(n-1)=2n-1$。

哈夫曼树用**顺序存储**（一维结构数组）实现最简单。每个节点需要四个域：权值、双亲、左孩子、右孩子。

```c
typedef struct {
    int weight;
    int parent, lchild, rchild;
} HTNode, *HuffmanTree;
```

数组大小取 $2n$，0 号单元不用，节点存放在 $1\sim 2n-1$，其中 $m=2n-1$ 是根。初始化时把所有单元的 `parent`、`lchild`、`rchild` 置 0（0 表示“无”），前 $n$ 个单元填入叶子的权值。

```c
void CreateHuffmanTree(HuffmanTree ht, int w[], int n) {
    int m = 2 * n - 1;
    for (int i = 1; i <= m; i++)
        ht[i].parent = ht[i].lchild = ht[i].rchild = 0;
    for (int i = 1; i <= n; i++)
        ht[i].weight = w[i];
    for (int i = n + 1; i <= m; i++) {
        Select(ht, i - 1, &s1, &s2);   // 在 1..i-1 中选 parent==0 的两个权最小者
        ht[s1].parent = ht[s2].parent = i;
        ht[i].lchild = s1;
        ht[i].rchild = s2;
        ht[i].weight = ht[s1].weight + ht[s2].weight;
    }
}
```

`Select` 只在 `parent==0`（仍是根）的节点中挑选，因而不会重复使用已合并的节点。例如 $n=8$ 时 $m=15$，数组开 16 个单元，只用 $1\sim15$；构造完成后，根 15 的 `parent` 为 0，叶子 1–8 的 `lchild`、`rchild` 均为 0。

> **★考点**：$n$ 个叶子的哈夫曼树共有 $2n-1$ 个节点、$n-1$ 个度为 2 的节点、无度为 1 的节点。

<figure class="cpd-figure not-content" id="wz-w3-fig-13">
  <svg viewBox="0 0 700 288" role="img" aria-label="哈夫曼树贪心两小合并四步演化过程与 HTNode 一维静态三叉链表顺序存储表">
    <defs>
      <marker id="wz-w3-arr-13h" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="14" width="356" height="260" rx="8"/>
    <rect class="fig-box-subtle" x="384" y="14" width="300" height="260" rx="8"/>
    <g class="fig-line" marker-end="url(#wz-w3-arr-13h)">
      <line x1="194" y1="74" x2="194" y2="92"/>
      <line x1="194" y1="126" x2="194" y2="144"/>
      <line x1="194" y1="178" x2="194" y2="196"/>
    </g>
    <rect class="fig-box" x="28" y="46" width="332" height="28" rx="4"/>
    <rect class="fig-box" x="28" y="96" width="332" height="28" rx="4"/>
    <rect class="fig-box" x="28" y="148" width="332" height="28" rx="4"/>
    <rect class="fig-box-accent" x="28" y="200" width="332" height="30" rx="4"/>
    <rect class="fig-box" x="398" y="42" width="272" height="178" rx="4"/>
    <g class="fig-divider">
      <line x1="398" y1="62" x2="670" y2="62"/><line x1="398" y1="82" x2="670" y2="82"/>
      <line x1="398" y1="102" x2="670" y2="102"/><line x1="398" y1="122" x2="670" y2="122"/>
      <line x1="398" y1="142" x2="670" y2="142"/><line x1="398" y1="162" x2="670" y2="162"/>
      <line x1="398" y1="182" x2="670" y2="182"/><line x1="398" y1="202" x2="670" y2="202"/>
      <line x1="444" y1="42" x2="444" y2="202"/><line x1="504" y1="42" x2="504" y2="202"/>
      <line x1="560" y1="42" x2="560" y2="202"/><line x1="615" y1="42" x2="615" y2="202"/>
    </g>
    <rect class="fig-box-green" x="398" y="228" width="272" height="36" rx="6"/>
    <g font-size="11">
      <text class="fig-title" x="194" y="34" text-anchor="middle" font-size="11.5">贪心合并四步曲（叶子权 7, 5, 2, 4）</text>
      <text class="fig-label" x="40" y="64">初始森林：&#123;7&#125;, &#123;5&#125;,</text>
      <text class="fig-orange" x="158" y="64">&#123;2&#125;, &#123;4&#125;</text>
      <text class="fig-muted" x="220" y="64" font-size="10.5">← 选两最小根</text>
      <text class="fig-label" x="40" y="114">第 1 次合并：&#123;7&#125;,</text>
      <text class="fig-orange" x="148" y="114">&#123;5&#125;, &#123;6&#125;</text>
      <text class="fig-muted" x="210" y="114" font-size="10.5">（2+4=6 入森林）</text>
      <text class="fig-label" x="40" y="166">第 2 次合并：</text>
      <text class="fig-orange" x="122" y="166">&#123;7&#125;, &#123;11&#125;</text>
      <text class="fig-muted" x="192" y="166" font-size="10.5">（5+6=11 入森林）</text>
      <text class="fig-accent" x="40" y="219">第 3 次合并：&#123;18&#125; 单根建成（7 + 11 = 18）</text>
      <text class="fig-green" x="194" y="254" text-anchor="middle">最优 WPL = 7×1 + 5×2 + (2+4)×3 = 35 &lt; 满树 36</text>
    </g>
    <g font-size="10.5" text-anchor="middle">
      <text class="fig-title" x="534" y="33" font-size="11.5">ht[1..2n-1] 静态数组（0 号不用）</text>
      <text class="fig-title" x="421" y="56">下标</text><text class="fig-title" x="474" y="56">weight</text>
      <text class="fig-title" x="532" y="56">parent</text><text class="fig-title" x="587" y="56">lchild</text><text class="fig-title" x="642" y="56">rchild</text>
      <text class="fig-muted" x="421" y="76">1(a)</text><text class="fig-blue" x="474" y="76">7</text><text class="fig-label" x="532" y="76">7</text><text class="fig-muted" x="587" y="76">0</text><text class="fig-muted" x="642" y="76">0</text>
      <text class="fig-muted" x="421" y="96">2(b)</text><text class="fig-blue" x="474" y="96">5</text><text class="fig-label" x="532" y="96">6</text><text class="fig-muted" x="587" y="96">0</text><text class="fig-muted" x="642" y="96">0</text>
      <text class="fig-muted" x="421" y="116">3(c)</text><text class="fig-blue" x="474" y="116">2</text><text class="fig-label" x="532" y="116">5</text><text class="fig-muted" x="587" y="116">0</text><text class="fig-muted" x="642" y="116">0</text>
      <text class="fig-muted" x="421" y="136">4(d)</text><text class="fig-blue" x="474" y="136">4</text><text class="fig-label" x="532" y="136">5</text><text class="fig-muted" x="587" y="136">0</text><text class="fig-muted" x="642" y="136">0</text>
      <text class="fig-orange" x="421" y="156">5</text><text class="fig-orange" x="474" y="156">6</text><text class="fig-label" x="532" y="156">6</text><text class="fig-blue" x="587" y="156">3</text><text class="fig-blue" x="642" y="156">4</text>
      <text class="fig-orange" x="421" y="176">6</text><text class="fig-orange" x="474" y="176">11</text><text class="fig-label" x="532" y="176">7</text><text class="fig-blue" x="587" y="176">2</text><text class="fig-blue" x="642" y="176">5</text>
      <text class="fig-accent" x="421" y="196">7(根)</text><text class="fig-accent" x="474" y="196">18</text><text class="fig-accent" x="532" y="196">0</text><text class="fig-blue" x="587" y="196">1</text><text class="fig-blue" x="642" y="196">6</text>
      <text class="fig-muted" x="534" y="215" font-size="10">WPL 亦等于所有非叶分支结点权值之和：6+11+18 = 35</text>
      <text class="fig-green" x="534" y="244">总结点 2n-1 = 7（n₀=4，n₂=3，必有 n₁=0）</text>
      <text class="fig-muted" x="534" y="258" font-size="9.5">Select 仅挑 parent == 0 的根，合并后置双亲下标</text>
    </g>
  </svg>
  <figcaption>哈夫曼树贪心构造与 HTNode[1..2n-1] 静态三叉链表：无度为 1 的结点，非叶结点权和即 WPL</figcaption>
</figure>

### 哈夫曼编码

定长编码给每个字符相同位数（如 ASCII 用 8 位），实现简单但浪费空间。变长编码让高频字符用短码、低频字符用长码，可压缩存储；但随意缩短会产生歧义：若 `a=0`、`b=00`，则 `0000` 既可读作 4 个 `a`，也可读作 2 个 `b`，根源是 `a` 的编码是 `b` 编码的前缀。

**前缀编码**：任一字符的编码都不是其他字符编码的前缀，译码时就不会有歧义。

哈夫曼编码的构造步骤：

1. 统计每个字符在电文中出现的频率（或概率），以其为叶子权值；
2. 按哈夫曼算法构造哈夫曼树；
3. 约定**左分支标 0、右分支标 1**；
4. 从根到某叶子的路径上，各分支的 0/1 依次组成该叶子所代表字符的编码。

以权值 $7,5,2,4$ 的四个字符 $a,b,c,d$ 为例，编码为 $a=0$、$b=10$、$c=110$、$d=111$。

<figure class="cpd-figure not-content" id="wz-fig-15">
  <svg viewBox="0 0 700 288" role="img" aria-label="哈夫曼树左0右1前缀编码构造及与有歧义非前缀编码对比">
    <rect class="fig-box-subtle" x="16" y="14" width="420" height="260" rx="8"/>
    <rect class="fig-box-subtle" x="448" y="14" width="236" height="260" rx="8"/>
    <g class="fig-line">
      <line x1="210" y1="54" x2="112" y2="122"/>
      <line x1="210" y1="54" x2="308" y2="122"/>
      <line x1="308" y1="122" x2="240" y2="188"/>
      <line x1="308" y1="122" x2="366" y2="188"/>
      <line x1="366" y1="188" x2="318" y2="246"/>
      <line x1="366" y1="188" x2="404" y2="246"/>
    </g>
    <circle class="fig-box-accent" cx="210" cy="54" r="17"/>
    <circle class="fig-box" cx="308" cy="122" r="17"/>
    <circle class="fig-box" cx="366" cy="188" r="17"/>
    <g class="fig-box-green">
      <circle cx="112" cy="122" r="18"/>
      <circle cx="240" cy="188" r="18"/>
      <circle cx="318" cy="246" r="18"/>
      <circle cx="404" cy="246" r="18"/>
    </g>
    <g class="fig-box">
      <rect x="150" y="78" width="18" height="18" rx="4"/><rect x="252" y="78" width="18" height="18" rx="4"/>
      <rect x="264" y="144" width="18" height="18" rx="4"/><rect x="330" y="144" width="18" height="18" rx="4"/>
      <rect x="332" y="206" width="18" height="18" rx="4"/><rect x="378" y="206" width="18" height="18" rx="4"/>
    </g>
    <rect class="fig-box" x="462" y="44" width="208" height="104" rx="6"/>
    <rect class="fig-box-red" x="462" y="158" width="208" height="102" rx="6"/>
    <g font-size="11.5" text-anchor="middle">
      <text class="fig-title" x="226" y="32">哈夫曼编码树（左分支标 0，右分支标 1）</text>
      <text class="fig-accent" x="210" y="58">18</text>
      <text class="fig-green" x="112" y="126">a:7</text><text class="fig-label" x="308" y="126">11</text>
      <text class="fig-green" x="240" y="192">b:5</text><text class="fig-label" x="366" y="192">6</text>
      <text class="fig-green" x="318" y="250">c:2</text><text class="fig-green" x="404" y="250">d:4</text>
      <text class="fig-blue" x="159" y="91">0</text><text class="fig-orange" x="261" y="91">1</text>
      <text class="fig-blue" x="273" y="157">0</text><text class="fig-orange" x="339" y="157">1</text>
      <text class="fig-blue" x="341" y="219">0</text><text class="fig-orange" x="387" y="219">1</text>
      <text class="fig-title" x="566" y="32">前缀码性质与歧义对比</text>
    </g>
    <g font-size="11">
      <text class="fig-accent" x="86" y="126" text-anchor="end">a → 0</text>
      <text class="fig-accent" x="214" y="192" text-anchor="end">b → 10</text>
      <text class="fig-accent" x="292" y="250" text-anchor="end">c → 110</text>
      <text class="fig-accent" x="30" y="246">总电文长 = WPL = 35 位</text>
      <text class="fig-green" x="472" y="64">✓ 哈夫曼前缀码（字符全在叶）：</text>
      <text class="fig-label" x="472" y="83">a=0, b=10, c=110, d=111</text>
      <text class="fig-muted" x="472" y="102" font-size="10.5">任一叶子绝非另一叶子祖先，</text>
      <text class="fig-muted" x="472" y="119" font-size="10.5">编码互不为前缀，即时无歧义译码</text>
      <text class="fig-muted" x="472" y="138" font-size="10.5">（定长2位需 (7+5+2+4)×2 = 36位）</text>
      <text class="fig-red" x="472" y="178">✗ 非前缀码反例（字符在内部结点）：</text>
      <text class="fig-label" x="472" y="197">若令 a = 0，b = 00（0 是 00 前缀）</text>
      <text class="fig-red" x="472" y="217">收到位流 0000 产生致命二义性：</text>
      <text class="fig-muted" x="472" y="236" font-size="10.5">既可译为 aaaa，也可译为 bb 或 aab</text>
    </g>
  </svg>
  <figcaption>哈夫曼树与最优前缀编码：高频字符近根用短码，总码长等于最小 WPL = 35</figcaption>
</figure>

哈夫曼编码的两个性质：

- **前缀码**：所有字符都位于叶子上，任一叶子都不是另一叶子的祖先，故其编码不可能是别的编码的前缀。
- **最优前缀码**：编码位数就是叶子深度，编码总长等于 $\sum f_i l_i$（各字符频率乘其码长），恰好等于哈夫曼树的 $WPL$；哈夫曼树的 $WPL$ 最小，所以编码总长最短。

> **★考点**：哈夫曼编码不唯一（左右子树可互换），但各字符的码长分布与 $WPL$ 不变。

> **交互演示**：[哈夫曼树与编码](/lab/chapter-6/#lab-huffman)

### 哈夫曼编码的算法实现与文件编解码

从根到叶子逐位记录不方便写算法，实现时**从叶子向根回溯**：若当前节点是双亲的左孩子则记 0，是右孩子则记 1，直到双亲为 0（到达根）。由于得到的是编码的逆序，需把 0/1 从字符数组末尾向前填，最后从起始位置整体复制。

```c
void CreateHuffmanCode(HuffmanTree ht, HuffmanCode hc, int n) {
    char *cd = (char *)malloc(n * sizeof(char));   // 最长 n-1 位，再留结束符
    cd[n - 1] = '\0';
    for (int i = 1; i <= n; i++) {                 // 依次求 n 个叶子的编码
        int start = n - 1, c = i, f = ht[i].parent;
        while (f != 0) {                           // 未到根则继续回溯
            if (ht[f].lchild == c) cd[--start] = '0';
            else                   cd[--start] = '1';
            c = f;
            f = ht[f].parent;
        }
        hc[i] = (char *)malloc((n - start) * sizeof(char));
        strcpy(hc[i], &cd[start]);
    }
    free(cd);
}
```

树高最多 $n-1$，编码最多 $n-1$ 位，故 `cd` 长度取 $n$ 足够。`hc` 是字符串数组（指针数组），共 $n$ 项，每项指向一个 0/1 串。

**文件编码**：

1. 扫描文件，统计出现了哪些字符及其频度；
2. 以频度为权构造哈夫曼树，求出各字符的编码 `hc`；
3. 顺序读取原文，每读一个字符就到 `hc` 中查出其编码，依次拼接成 0/1 位流写出。

**文件译码**：

1. 用相同的字符频度重建同一棵哈夫曼树（译码端必须持有同样的码表）；
2. 从根出发逐位读入位流：读到 0 走左孩子，读到 1 走右孩子；
3. 走到叶子即输出该叶子代表的字符，然后回到根继续，直到位流结束。

例：一个含 378 个字符的英文文件，用 8 位 ASCII 需 $378\times8=3024$ 位；用哈夫曼编码只需 1596 位，约为原来的一半，且可完整还原，属于**无损压缩**。

> **注意**：编码和译码必须使用同一棵哈夫曼树；编码结果中不能直接看出字符边界，译码只能依靠“到叶子才输出”这一规则。

<figure class="cpd-figure not-content" id="wz-w3-fig-14">
  <svg viewBox="0 0 700 248" role="img" aria-label="哈夫曼编码从叶子向根逆序回溯填 cd[--start] 缓冲区及位流逐位走树无损译码过程">
    <defs>
      <marker id="wz-w3-arr-14d" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="14" width="332" height="220" rx="8"/>
    <rect class="fig-box-subtle" x="360" y="14" width="324" height="220" rx="8"/>
    <g class="fig-line" marker-end="url(#wz-w3-arr-14d)">
      <line x1="226" y1="152" x2="180" y2="152"/>
      <line x1="180" y1="152" x2="134" y2="152"/>
      <line x1="134" y1="152" x2="88" y2="152"/>
    </g>
    <rect class="fig-box" x="28" y="46" width="308" height="62" rx="6"/>
    <rect class="fig-box-dashed" x="42" y="162" width="46" height="32" rx="4"/>
    <rect class="fig-box-orange" x="88" y="162" width="46" height="32" rx="4"/>
    <rect class="fig-box-orange" x="134" y="162" width="46" height="32" rx="4"/>
    <rect class="fig-box-blue" x="180" y="162" width="46" height="32" rx="4"/>
    <rect class="fig-box-purple" x="226" y="162" width="54" height="32" rx="4"/>
    <rect class="fig-box" x="374" y="46" width="296" height="118" rx="6"/>
    <rect class="fig-box-green" x="374" y="174" width="296" height="46" rx="6"/>
    <g font-size="11">
      <text class="fig-title" x="182" y="34" text-anchor="middle" font-size="11.5">① 编码实现：叶→根回溯逆填 cd[--start]</text>
      <text class="fig-label" x="38" y="66">求叶子 c(下标3) 编码的回溯链：</text>
      <text class="fig-blue" x="38" y="84">3 是 5 的左孩(‘0’) → 5 是 6 的右孩(‘1’)</text>
      <text class="fig-orange" x="38" y="100">→ 6 是根 7 的右孩(‘1’)，达 f==0 停止</text>
      <text class="fig-muted" x="160" y="142" text-anchor="middle" font-size="10">start 从 n-1 递减左移，strcpy(&amp;cd[start]) 正序导出 "110"</text>
      <text class="fig-muted" x="160" y="216" text-anchor="middle" font-size="10.5">树高 ≤ n-1 ⇒ 最长码长 n-1 位，cd[n] 恰好够用</text>
      <text class="fig-title" x="522" y="34" text-anchor="middle" font-size="11.5">② 译码状态机：根出发逐位走树，到叶输出</text>
      <text class="fig-accent" x="386" y="68">输入连续位流：0 1 0 1 1 0 1 1 1（无分隔符！）</text>
      <text class="fig-label" x="386" y="90">• 读 0：18 ──(左)──&gt; 叶子 a，输出 ‘a’，回根 18</text>
      <text class="fig-label" x="386" y="110">• 读 1,0：18→11→叶子 b，输出 ‘b’，回根 18</text>
      <text class="fig-label" x="386" y="130">• 读 1,1,0：18→11→6→叶子 c，输出 ‘c’，回根</text>
      <text class="fig-label" x="386" y="150">• 读 1,1,1：18→11→6→叶子 d，输出 ‘d’，结束</text>
      <text class="fig-green" x="386" y="194">无损还原原文："abcd"（收发双方须共享同一哈夫曼树）</text>
      <text class="fig-muted" x="386" y="211" font-size="10">核心判据：ht[p].lchild == 0 &amp;&amp; ht[p].rchild == 0 即达叶子</text>
    </g>
    <g font-size="11" text-anchor="middle">
      <text class="fig-muted" x="65" y="182">—</text>
      <text class="fig-orange" x="111" y="182">'1'</text>
      <text class="fig-orange" x="157" y="182">'1'</text>
      <text class="fig-blue" x="203" y="182">'0'</text>
      <text class="fig-purple" x="253" y="182">'\0'</text>
      <text class="fig-accent" x="111" y="128" font-size="10">start</text>
    </g>
  </svg>
  <figcaption>哈夫曼编解码工程闭环：编码靠 parent 域自底向上逆填缓冲区，译码靠 lchild/rchild 自顶向下走树</figcaption>
</figure>

## 第6章 图

### 图的定义与四种逻辑结构

图记为 $G=(V,E)$：$V$ 是**顶点**（vertex）的**有穷非空**集合，$E$ 是**边**（edge）的有穷集合，可以为空（只有顶点没有边的图仍是图，没有顶点则不是图）。

| 逻辑结构 | 数据元素之间的关系 |
| --- | --- |
| 集合 | 同属一个集合，元素间无其他关系 |
| 线性结构 | 一对一：至多一个直接前驱、一个直接后继 |
| 树形结构 | 一对多：一个前驱、多个后继；根无前驱，叶无后继 |
| 图结构 | **多对多**：任意顶点都可能有多个前驱、多个后继 |

正因为一个顶点的前驱、后继个数都不定，图无法像线性表、树那样用“指针域固定”的多重链表直接表达，其存储结构需要专门设计。

### 无向图、有向图与完全图

- **无向图**：每条边都没有方向，记作 $(v_i,v_j)$，圆括号表示无序。
- **有向图**：每条边都有方向，记作 $\langle v_i,v_j\rangle$，尖括号表示有序；$v_i$ 为**弧尾（起点）**，$v_j$ 为**弧头（终点）**。有向图中的边专称**弧**。
- **完全图**：任意两个顶点之间都有边相连。
  - 无向完全图有 $n$ 个顶点时，边数为 $\dfrac{n(n-1)}{2}$（任取两点一条边，即 $C_n^2$）。
  - 有向完全图任意两点之间两个方向各有一条弧，弧数为 $n(n-1)$。

> **★考点**：$n$ 个顶点的无向图边数范围是 $0\sim\dfrac{n(n-1)}{2}$；有向图是 $0\sim n(n-1)$。

<figure class="cpd-figure not-content" id="wz-w4-fig-1">
  <svg viewBox="0 0 680 202" role="img" aria-labelledby="wz-fig-16">
    <title id="wz-fig-16">无向图、有向图与完全图 K₄ 对比</title>
    <defs>
      <marker id="wz-arr-16" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M1.5,1.5 L8.5,5 L1.5,8.5" fill="none" stroke="context-stroke" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
      </marker>
    </defs>
    <text class="fig-title" x="115" y="20" text-anchor="middle" font-size="12.5">无向图</text>
    <text class="fig-title" x="340" y="20" text-anchor="middle" font-size="12.5">有向图</text>
    <text class="fig-title" x="560" y="20" text-anchor="middle" font-size="12.5">无向完全图 K₄</text>
    <g class="fig-line">
      <line x1="115" y1="54" x2="65" y2="134"/>
      <line x1="115" y1="54" x2="165" y2="134"/>
      <line x1="65" y1="134" x2="165" y2="134"/>
      <line x1="515" y1="54" x2="605" y2="54"/>
      <line x1="515" y1="138" x2="605" y2="138"/>
      <line x1="515" y1="54" x2="515" y2="138"/>
      <line x1="605" y1="54" x2="605" y2="138"/>
      <line x1="515" y1="54" x2="605" y2="138"/>
      <line x1="605" y1="54" x2="515" y2="138"/>
    </g>
    <g stroke="var(--sl-color-accent)" stroke-width="1.4" fill="none" marker-end="url(#wz-arr-16)">
      <line x1="331" y1="68" x2="300" y2="118"/>
      <line x1="306" y1="134" x2="371" y2="134"/>
      <line x1="381" y1="119" x2="350" y2="69"/>
    </g>
    <g class="fig-box-blue">
      <circle cx="115" cy="54" r="16"/><circle cx="65" cy="134" r="16"/><circle cx="165" cy="134" r="16"/>
      <circle cx="340" cy="54" r="16"/><circle cx="290" cy="134" r="16"/><circle cx="390" cy="134" r="16"/>
      <circle cx="515" cy="54" r="16"/><circle cx="605" cy="54" r="16"/><circle cx="515" cy="138" r="16"/><circle cx="605" cy="138" r="16"/>
    </g>
    <g class="fig-blue" font-size="12.5" text-anchor="middle">
      <text x="115" y="59">A</text><text x="65" y="139">B</text><text x="165" y="139">C</text>
      <text x="340" y="59">A</text><text x="290" y="139">B</text><text x="390" y="139">C</text>
      <text x="515" y="59">A</text><text x="605" y="59">B</text><text x="515" y="143">C</text><text x="605" y="143">D</text>
    </g>
    <g class="fig-muted" font-size="11.5" text-anchor="middle">
      <text x="115" y="182">边 (A,B)、(A,C)、(B,C)</text>
      <text x="340" y="182">弧 A→B、B→C、C→A</text>
      <text x="560" y="182">6 条边 = 4×3/2</text>
    </g>
  </svg>
  <figcaption>无向图、有向图与完全图：Kₙ 任意两点都有边，边数为 n(n−1)/2</figcaption>
</figure>

### 稀疏图、稠密图与网

- **稀疏图**：边（弧）很少的图，通常指 $e<n\log n$（$n$ 为顶点数）。
- **稠密图**：边（弧）较多的图，与稀疏图相对。
- **网**：边或弧带有**权**（具有特定含义的数值，如距离、时间、代价）的图。权在不同应用中含义不同。

> **注意**：有向图的边称弧；“网”不是一种新的逻辑结构，只是带权的图。

<figure class="cpd-figure not-content" id="wz-w4-fig-2">
  <svg viewBox="0 0 680 210" role="img" aria-labelledby="wz-fig-17">
    <title id="wz-fig-17">稀疏图、稠密图 K₅ 与带权网对比</title>
    <g class="fig-line">
      <line x1="70" y1="58" x2="150" y2="58"/>
      <line x1="150" y1="58" x2="110" y2="108"/>
      <line x1="110" y1="108" x2="70" y2="158"/>
      <line x1="110" y1="108" x2="150" y2="158"/>
      <line x1="340" y1="48" x2="404" y2="90"/><line x1="404" y1="90" x2="380" y2="156"/>
      <line x1="380" y1="156" x2="300" y2="156"/><line x1="300" y1="156" x2="276" y2="90"/>
      <line x1="276" y1="90" x2="340" y2="48"/>
      <line x1="340" y1="48" x2="380" y2="156"/><line x1="340" y1="48" x2="300" y2="156"/>
      <line x1="404" y1="90" x2="276" y2="90"/><line x1="404" y1="90" x2="300" y2="156"/>
      <line x1="276" y1="90" x2="380" y2="156"/>
      <line x1="515" y1="58" x2="615" y2="58"/>
      <line x1="515" y1="58" x2="615" y2="152"/>
      <line x1="515" y1="58" x2="515" y2="152"/>
      <line x1="515" y1="152" x2="615" y2="152"/>
      <line x1="615" y1="58" x2="615" y2="152"/>
    </g>
    <g class="fig-box-blue">
      <circle cx="70" cy="58" r="15"/><circle cx="150" cy="58" r="15"/><circle cx="110" cy="108" r="15"/><circle cx="70" cy="158" r="15"/><circle cx="150" cy="158" r="15"/>
      <circle cx="340" cy="48" r="15"/><circle cx="404" cy="90" r="15"/><circle cx="380" cy="156" r="15"/><circle cx="300" cy="156" r="15"/><circle cx="276" cy="90" r="15"/>
      <circle cx="515" cy="58" r="15"/><circle cx="615" cy="58" r="15"/><circle cx="515" cy="152" r="15"/><circle cx="615" cy="152" r="15"/>
    </g>
    <g class="fig-blue" font-size="12" text-anchor="middle">
      <text x="70" y="62">A</text><text x="150" y="62">B</text><text x="110" y="112">C</text><text x="70" y="162">D</text><text x="150" y="162">E</text>
      <text x="340" y="52">A</text><text x="404" y="94">B</text><text x="380" y="160">C</text><text x="300" y="160">D</text><text x="276" y="94">E</text>
      <text x="515" y="62">A</text><text x="615" y="62">B</text><text x="515" y="156">C</text><text x="615" y="156">D</text>
    </g>
    <g class="fig-accent" font-size="11.5" text-anchor="middle">
      <text x="565" y="48">4</text>
      <text x="502" y="109">5</text>
      <text x="576" y="101">9</text>
      <text x="628" y="109">8</text>
      <text x="565" y="168">6</text>
    </g>
    <g class="fig-title" font-size="12.5" text-anchor="middle">
      <text x="110" y="20">稀疏图（5 点 4 边）</text>
      <text x="340" y="20">稠密图 K₅（10 边）</text>
      <text x="565" y="20">网（带权图）</text>
    </g>
    <g class="fig-muted" font-size="11.5" text-anchor="middle">
      <text x="110" y="192">e 远小于 n log n</text>
      <text x="340" y="192">接近 n(n−1)/2</text>
      <text x="565" y="192">边带距离 / 代价权值</text>
    </g>
  </svg>
  <figcaption>稀疏图、稠密图与带权网对比</figcaption>
</figure>

### 邻接、关联与顶点的度

**邻接**描述顶点与顶点的关系：

- 无向图中若存在 $(v_i,v_j)$，则 $v_i$ 与 $v_j$ 互为**邻接点**。
- 有向图中若存在 $\langle v_i,v_j\rangle$，则称 $v_i$ **邻接到** $v_j$，$v_j$ **邻接于** $v_i$（方向不可逆）。

**关联（依附）**描述边与顶点的关系：一条边（弧）与它的两个端点**相关联**，也称该边**依附于**这两个顶点。

**顶点的度** $TD(v)$：与该顶点相关联的边（弧）的数目。

- 无向图：度就是关联边的条数。
- 有向图：度分**入度** $ID(v)$（以 $v$ 为弧头的弧数）与**出度** $OD(v)$（以 $v$ 为弧尾的弧数），且
$$
TD(v)=ID(v)+OD(v)
$$

**有向树**：有且仅有一个顶点入度为 $0$，其余顶点入度均为 $1$ 的有向图。它与普通树的区别在于边带方向。

### 路径、回路与简单路径

- **路径**：由若干条**接续的边**连接而成的**顶点序列**（如 $v_1,v_3,v_4$）。
- **路径长度**：路径上边（弧）的数目；若为网，则是路径上各边权值之和。
- **回路（环）**：第一个顶点与最后一个顶点相同的路径。
- **简单路径**：路径上除起点、终点可以相同外，其余顶点均不重复。
- **简单回路（简单环）**：既是简单路径又是回路的路径，即除首尾外顶点不重复。

> **注意**：判断简单路径看的是**顶点**是否重复，不是边；绕一圈回到中间某个已访问顶点，就不再是简单路径。

<figure class="cpd-figure not-content" id="wz-w4-fig-3">
  <svg viewBox="0 0 680 190" role="img" aria-labelledby="wz-fig-18">
    <title id="wz-fig-18">路径、回路与简单路径</title>
    <defs>
      <marker id="wz-arr-18" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M1.5,1.5 L8.5,5 L1.5,8.5" fill="none" stroke="context-stroke" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
      </marker>
    </defs>
    <g class="fig-title" font-size="12.5" text-anchor="middle">
      <text x="118" y="20">路径 A → B → C</text>
      <text x="340" y="20">回路 A → B → C → A</text>
      <text x="562" y="20">简单路径 A → B → C → D</text>
    </g>
    <g stroke="var(--sl-color-accent)" stroke-width="1.5" fill="none" marker-end="url(#wz-arr-18)">
      <line x1="64" y1="84" x2="99" y2="84"/>
      <line x1="136" y1="84" x2="171" y2="84"/>
      <line x1="331" y1="70" x2="300" y2="120"/>
      <line x1="306" y1="136" x2="371" y2="136"/>
      <line x1="381" y1="121" x2="350" y2="71"/>
      <line x1="510" y1="86" x2="544" y2="66"/>
      <line x1="576" y1="67" x2="606" y2="88"/>
      <line x1="606" y1="108" x2="578" y2="129"/>
    </g>
    <g class="fig-box-blue">
      <circle cx="48" cy="84" r="16"/><circle cx="118" cy="84" r="16"/><circle cx="188" cy="84" r="16"/>
      <circle cx="340" cy="56" r="16"/><circle cx="290" cy="136" r="16"/><circle cx="390" cy="136" r="16"/>
      <circle cx="496" cy="95" r="16"/><circle cx="562" cy="58" r="16"/><circle cx="620" cy="97" r="16"/><circle cx="562" cy="138" r="16"/>
    </g>
    <g class="fig-blue" font-size="12.5" text-anchor="middle">
      <text x="48" y="89">A</text><text x="118" y="89">B</text><text x="188" y="89">C</text>
      <text x="340" y="61">A</text><text x="290" y="141">B</text><text x="390" y="141">C</text>
      <text x="496" y="100">A</text><text x="562" y="63">B</text><text x="620" y="102">C</text><text x="562" y="143">D</text>
    </g>
    <g class="fig-muted" font-size="11.5" text-anchor="middle">
      <text x="118" y="172">顶点不重复</text>
      <text x="340" y="172">起点与终点相同</text>
      <text x="562" y="172">除首尾外不重复</text>
    </g>
  </svg>
  <figcaption>路径、回路与简单路径判别（看顶点是否重复，而非看边）</figcaption>
</figure>

### 连通图、连通分量与生成树

- **连通图**（无向图）：任意两个顶点之间都存在路径。
- **强连通图**（有向图）：任意两个顶点 $v_i,v_j$ 之间，既存在 $v_i\to v_j$ 的路径，也存在 $v_j\to v_i$ 的路径。
- **子图**：$G_1=(V_1,E_1)$ 满足 $V_1\subseteq V$ 且 $E_1\subseteq E$。
- **连通分量**：无向图的**极大连通子图**——子图连通，且再加入任何一个顶点都会变得不连通。有向图对应概念为**强连通分量**（极大强连通子图）。

**极小连通子图**：顶点数保持不变、边数达到最小的连通子图，删去任意一条边即不再连通。含 $n$ 个顶点的连通图，其极小连通子图有 $n-1$ 条边，即**生成树**。

> **★考点**：非连通图的连通分量个数可以这样求——从每个未访问顶点出发做一次遍历，遍历（DFS/BFS）被调用的次数就是连通分量数。

| 概念 | 具体例子 |
| --- | --- |
| 无向图 / 有向图 | 城市间双向公路 / 单行道、微博关注 |
| 完全图 | 4 个城市两两直飞：无向图 $4\times3/2=6$ 条边；有向图 $4\times3=12$ 条弧 |
| 稀疏图 / 稠密图 | $n=1000,e=2000$ 是稀疏图；$e$ 接近 $n(n-1)/2$ 是稠密图 |
| 网 | 公路地图，边上的权值是两城距离 |
| 路径 / 回路 / 简单路径 | $A\to B\to C\to D$ / $A\to B\to C\to A$ / 路径上顶点不重复 |
| 连通图 / 连通分量 | 全国公路网连通 / 三个海岛各自成连通分量 |
| 生成树 | 4 个城市用 3 条边全部连通且无回路 |
| 邻接矩阵 | 4 个顶点用 $4\times4$ 矩阵，$a_{ij}=1$ 表示有边 |

<figure class="cpd-figure not-content" id="wz-w4-fig-4">
  <svg viewBox="0 0 680 202" role="img" aria-labelledby="wz-fig-19">
    <title id="wz-fig-19">连通图、两个连通分量与生成树</title>
    <g class="fig-title" font-size="12.5" text-anchor="middle">
      <text x="115" y="20">连通图</text>
      <text x="340" y="20">两个连通分量</text>
      <text x="565" y="20">生成树（3 条实线）</text>
    </g>
    <g class="fig-line">
      <line x1="70" y1="64" x2="70" y2="144"/><line x1="70" y1="64" x2="160" y2="64"/>
      <line x1="160" y1="64" x2="160" y2="144"/><line x1="70" y1="144" x2="160" y2="144"/>
      <line x1="70" y1="64" x2="160" y2="144"/>
      <line x1="295" y1="64" x2="385" y2="64"/>
      <line x1="295" y1="144" x2="385" y2="144"/>
    </g>
    <g stroke="var(--sl-color-green)" stroke-width="1.8" fill="none">
      <line x1="520" y1="64" x2="520" y2="144"/>
      <line x1="520" y1="64" x2="610" y2="64"/>
      <line x1="520" y1="144" x2="610" y2="144"/>
    </g>
    <line stroke="var(--sl-color-gray-4)" stroke-width="1.4" stroke-dasharray="5 3" x1="610" y1="64" x2="610" y2="144"/>
    <g class="fig-box-blue">
      <circle cx="70" cy="64" r="15"/><circle cx="160" cy="64" r="15"/><circle cx="70" cy="144" r="15"/><circle cx="160" cy="144" r="15"/>
      <circle cx="295" cy="64" r="15"/><circle cx="385" cy="64" r="15"/><circle cx="295" cy="144" r="15"/><circle cx="385" cy="144" r="15"/>
      <circle cx="520" cy="64" r="15"/><circle cx="610" cy="64" r="15"/><circle cx="520" cy="144" r="15"/><circle cx="610" cy="144" r="15"/>
    </g>
    <g class="fig-blue" font-size="12" text-anchor="middle">
      <text x="70" y="68">A</text><text x="160" y="68">B</text><text x="70" y="148">C</text><text x="160" y="148">D</text>
      <text x="295" y="68">A</text><text x="385" y="68">B</text><text x="295" y="148">C</text><text x="385" y="148">D</text>
      <text x="520" y="68">A</text><text x="610" y="68">B</text><text x="520" y="148">C</text><text x="610" y="148">D</text>
    </g>
    <g class="fig-muted" font-size="11.5" text-anchor="middle">
      <text x="115" y="184">任意两点可达</text>
      <text x="340" y="184">A-B 与 C-D 互不连通</text>
      <text x="565" y="184">虚线为去掉的非树边</text>
    </g>
  </svg>
  <figcaption>连通图、连通分量与极小连通子图（生成树：n 顶点 n − 1 条边）</figcaption>
</figure>

### 图的抽象数据类型

图的 ADT 同样由三部分组成：

- **数据对象**：具有相同性质的顶点集合 $V$。
- **数据关系**：$R=\{\langle v_i,v_j\rangle\mid v_i,v_j\in V\}$，即顶点之间的边（弧）；网还可为每条边附加权值信息。
- **基本操作**：建图、查找顶点、取顶点信息、插入顶点/边、删除顶点/边等。

其中三个最重要的操作是：

1. **建图**：输入顶点集合与边集合，建立图的存储结构；
2. **深度优先遍历（DFS）**；
3. **广度优先遍历（BFS）**。

### 邻接矩阵表示法

图的顺序存储不叫顺序存储结构，而叫**数组表示法**，又称**邻接矩阵**。它用两个数组：

- **顶点表**：一维数组 `Vex[n]`，存放 $n$ 个顶点的信息；
- **邻接矩阵**：二维数组 `arcs[n][n]`，描述顶点之间的边。

无向图/有向图的邻接矩阵：

- $a_{ij}=1$ 当且仅当有边（弧）；
- 否则 $a_{ij}=0$。

网的邻接矩阵把 $1$ 换成权值：

- $a_{ij}=w_{ij}$ 当有边（弧）且权为 $w_{ij}$；
- 否则 $a_{ij}=\infty$。

| 图的类型 | 矩阵特点 | 度的计算 |
| --- | --- | --- |
| 无向图 | 对称矩阵，对角线全为 $0$ | $TD(v_i)=\sum_{j}a_{ij}$（第 $i$ 行之和） |
| 有向图 | 一般不对称 | $OD(v_i)=\sum_j a_{ij}$（行和），$ID(v_i)=\sum_j a_{ji}$（列和），$TD=OD+ID$ |
| 网 | 对称/不对称，无弧处为 $\infty$ | 同相应图，只是非零判断改为“非 $\infty$” |

无向图中每条边被两个顶点共享，矩阵中同一元素成对出现，故全图非零元素个数为 $2e$；有向图为 $e$。

> **注意**：自身到自身没有边，所以主对角线恒为 $0$；无向完全图的邻接矩阵是除对角线为 $0$ 外全为 $1$ 的矩阵。

### 邻接矩阵的建立与优缺点

以**无向网**为例，建图分四步：

1. 输入顶点数 `vexnum` 和边数 `arcnum`，存入图结构；
2. 循环输入每个顶点的信息，存入顶点表；
3. **初始化邻接矩阵**：双重循环把每个元素置为极大值（表示 $\infty$）；
4. **构造邻接矩阵**：循环 `arcnum` 次，每次输入一条边依附的两个顶点及权 $w$，在顶点表中查找这两个顶点的下标 $i,j$，置 `arcs[i][j]=arcs[j][i]=w`。

改成其他类型只需小改：

- **无向图**：初始化置 $0$，每条边的权视为 $1$，仍对称赋值；
- **有向网**：只置 `arcs[i][j]=w`，不置对称元素；
- **有向图**：初始化置 $0$，只置 `arcs[i][j]=1`。

**优点**：

- 直观、简单，可 $O(1)$ 判断任意两点之间是否有边；
- 计算顶点的度很方便（行和、列和）。

**缺点**：

- 空间复杂度为 $O(n^2)$，与边数无关；稀疏图会存储大量无效的 $0$（或 $\infty$），浪费空间；
- 增、删顶点要增删一行一列，操作麻烦；
- 统计边数必须遍历整个矩阵，$O(n^2)$，稀疏图下浪费时间。

> **★考点**：邻接矩阵适合**稠密图**，尤其完全图；稀疏图应选邻接表。

<figure class="cpd-figure not-content" id="wz-w4-fig-9">
  <svg viewBox="0 0 700 226" role="img" aria-labelledby="wz-w4-fig-9-title">
    <title id="wz-w4-fig-9-title">邻接矩阵表示法：无向图对称矩阵与有向网非对称矩阵对比</title>
    <defs>
      <marker id="wz-w4-arr-9" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <text class="fig-title" x="170" y="22" text-anchor="middle" font-size="12.5">无向图 G₁ 与对称邻接矩阵</text>
    <text class="fig-title" x="525" y="22" text-anchor="middle" font-size="12.5">有向网 G₂ 与非对称邻接矩阵</text>
    <line class="fig-divider" x1="350" y1="16" x2="350" y2="210"/>
    <g class="fig-line">
      <line x1="48" y1="68" x2="122" y2="68"/>
      <line x1="48" y1="68" x2="48" y2="142"/>
      <line x1="122" y1="68" x2="48" y2="142"/>
      <line x1="122" y1="68" x2="122" y2="142"/>
    </g>
    <g class="fig-box-blue">
      <circle cx="48" cy="68" r="14"/><circle cx="122" cy="68" r="14"/>
      <circle cx="48" cy="142" r="14"/><circle cx="122" cy="142" r="14"/>
    </g>
    <g class="fig-blue" font-size="11.5" text-anchor="middle">
      <text x="48" y="72">v₀</text><text x="122" y="72">v₁</text>
      <text x="48" y="146">v₂</text><text x="122" y="146">v₃</text>
    </g>
    <g class="fig-box">
      <rect x="174" y="56" width="136" height="112" rx="4"/>
    </g>
    <g class="fig-divider">
      <line x1="208" y1="56" x2="208" y2="168"/><line x1="242" y1="56" x2="242" y2="168"/><line x1="276" y1="56" x2="276" y2="168"/>
      <line x1="174" y1="84" x2="310" y2="84"/><line x1="174" y1="112" x2="310" y2="112"/><line x1="174" y1="140" x2="310" y2="140"/>
    </g>
    <g class="fig-muted" font-size="10.5" text-anchor="middle">
      <text x="191" y="48">v₀</text><text x="225" y="48">v₁</text><text x="259" y="48">v₂</text><text x="293" y="48">v₃</text>
      <text x="160" y="74">v₀</text><text x="160" y="102">v₁</text><text x="160" y="130">v₂</text><text x="160" y="158">v₃</text>
    </g>
    <g class="fig-label" font-size="11.5" text-anchor="middle">
      <text class="fig-muted" x="191" y="74">0</text><text class="fig-blue" x="225" y="74">1</text><text class="fig-blue" x="259" y="74">1</text><text x="293" y="74">0</text>
      <text class="fig-blue" x="191" y="102">1</text><text class="fig-muted" x="225" y="102">0</text><text class="fig-blue" x="259" y="102">1</text><text class="fig-blue" x="293" y="102">1</text>
      <text class="fig-blue" x="191" y="130">1</text><text class="fig-blue" x="225" y="130">1</text><text class="fig-muted" x="259" y="130">0</text><text x="293" y="130">0</text>
      <text x="191" y="158">0</text><text class="fig-blue" x="225" y="158">1</text><text x="259" y="158">0</text><text class="fig-muted" x="293" y="158">0</text>
    </g>
    <text class="fig-muted" x="170" y="198" text-anchor="middle" font-size="11">主对角线为 0，矩阵对称；第 i 行之和 = TD(vᵢ)</text>
    <g stroke="var(--sl-color-accent)" stroke-width="1.5" fill="none" marker-end="url(#wz-w4-arr-9)">
      <line x1="418" y1="68" x2="472" y2="68"/>
      <line x1="480" y1="81" x2="452" y2="128"/>
      <line x1="436" y1="128" x2="408" y2="81"/>
    </g>
    <g class="fig-box-accent">
      <circle cx="400" cy="68" r="14"/><circle cx="488" cy="68" r="14"/><circle cx="444" cy="142" r="14"/>
    </g>
    <g class="fig-accent" font-size="11.5" text-anchor="middle">
      <text x="400" y="72">v₀</text><text x="488" y="72">v₁</text><text x="444" y="146">v₂</text>
    </g>
    <g class="fig-accent" font-size="10.5" text-anchor="middle">
      <text x="444" y="58">5</text>
      <text x="478" y="114">3</text>
      <text x="410" y="114">8</text>
    </g>
    <g class="fig-box">
      <rect x="546" y="64" width="114" height="96" rx="4"/>
    </g>
    <g class="fig-divider">
      <line x1="584" y1="64" x2="584" y2="160"/><line x1="622" y1="64" x2="622" y2="160"/>
      <line x1="546" y1="96" x2="660" y2="96"/><line x1="546" y1="128" x2="660" y2="128"/>
    </g>
    <g class="fig-muted" font-size="10.5" text-anchor="middle">
      <text x="565" y="55">v₀</text><text x="603" y="55">v₁</text><text x="641" y="55">v₂</text>
      <text x="532" y="84">v₀</text><text x="532" y="116">v₁</text><text x="532" y="148">v₂</text>
    </g>
    <g class="fig-label" font-size="11.5" text-anchor="middle">
      <text class="fig-muted" x="565" y="84">0</text><text class="fig-accent" x="603" y="84">5</text><text class="fig-muted" x="641" y="84">∞</text>
      <text class="fig-muted" x="565" y="116">∞</text><text class="fig-muted" x="603" y="116">0</text><text class="fig-accent" x="641" y="116">3</text>
      <text class="fig-accent" x="565" y="148">8</text><text class="fig-muted" x="603" y="148">∞</text><text class="fig-muted" x="641" y="148">0</text>
    </g>
    <text class="fig-muted" x="525" y="198" text-anchor="middle" font-size="11">行非 ∞ 数 = 出度 OD；列非 ∞ 数 = 入度 ID</text>
  </svg>
  <figcaption>邻接矩阵表示法：无向图矩阵对称（$n^2$ 中存 $2e$ 个 1），有向网一般不对称（无弧置 $\infty$）</figcaption>
</figure>

### 邻接表表示法

**邻接表**是图的链式存储结构，由两部分组成：

- **顶点表**：一维数组，每个元素含 `data`（顶点信息）和 `firstarc`（指向第一条依附于该顶点的边）；
- **边表**：为每个顶点建立一条单链表，链上每个**边结点**含 `adjvex`（该边另一端点/邻接点在顶点表中的下标）、`nextarc`（下一条边），网还可加 `weight` 或 `info` 域。

<figure class="cpd-figure not-content" id="wz-w4-fig-5">
  <svg viewBox="0 0 680 232" role="img" aria-labelledby="wz-fig-20">
    <title id="wz-fig-20">无向图邻接表：顶点表数组与边表链表</title>
    <defs>
      <marker id="wz-arr-20" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M1.5,1.5 L8.5,5 L1.5,8.5" fill="none" stroke="context-stroke" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
      </marker>
    </defs>
    <text class="fig-title" x="115" y="22" text-anchor="middle" font-size="12.5">顶点表（一维数组）</text>
    <text class="fig-title" x="390" y="22" text-anchor="middle" font-size="12.5">边结点单链表（存邻接点下标）</text>
    <g class="fig-box">
      <rect x="30" y="34" width="170" height="34" rx="4"/>
      <rect x="30" y="80" width="170" height="34" rx="4"/>
      <rect x="30" y="126" width="170" height="34" rx="4"/>
    </g>
    <g class="fig-box-blue">
      <rect x="256" y="34" width="84" height="34" rx="4"/>
      <rect x="378" y="34" width="84" height="34" rx="4"/>
      <rect x="256" y="80" width="84" height="34" rx="4"/>
      <rect x="256" y="126" width="84" height="34" rx="4"/>
    </g>
    <g class="fig-divider">
      <line x1="120" y1="34" x2="120" y2="68"/><line x1="298" y1="34" x2="298" y2="68"/><line x1="420" y1="34" x2="420" y2="68"/>
      <line x1="120" y1="80" x2="120" y2="114"/><line x1="298" y1="80" x2="298" y2="114"/>
      <line x1="120" y1="126" x2="120" y2="160"/><line x1="298" y1="126" x2="298" y2="160"/>
    </g>
    <g font-size="12.5" text-anchor="middle">
      <text class="fig-label" x="75" y="56">0 | v₁</text><circle class="fig-dot" cx="160" cy="51" r="3"/>
      <text class="fig-blue" x="277" y="56">1</text><circle class="fig-dot" cx="319" cy="51" r="3"/>
      <text class="fig-blue" x="399" y="56">2</text><text class="fig-muted" x="441" y="56">∧</text>
      <text class="fig-label" x="75" y="102">1 | v₂</text><circle class="fig-dot" cx="160" cy="97" r="3"/>
      <text class="fig-blue" x="277" y="102">0</text><text class="fig-muted" x="319" y="102">∧</text>
      <text class="fig-label" x="75" y="148">2 | v₃</text><circle class="fig-dot" cx="160" cy="143" r="3"/>
      <text class="fig-blue" x="277" y="148">0</text><text class="fig-muted" x="319" y="148">∧</text>
    </g>
    <g stroke="var(--sl-color-accent)" stroke-width="1.5" fill="none" marker-end="url(#wz-arr-20)">
      <line x1="164" y1="51" x2="251" y2="51"/>
      <line x1="323" y1="51" x2="373" y2="51"/>
      <line x1="164" y1="97" x2="251" y2="97"/>
      <line x1="164" y1="143" x2="251" y2="143"/>
    </g>
    <g class="fig-muted" font-size="11.5">
      <text x="30" y="186">顶点结点：data | firstarc</text>
      <text x="30" y="206">边结点：adjvex（邻接点下标）| nextarc；图中 v₁—v₂、v₁—v₃ 无向边各存两次</text>
    </g>
  </svg>
  <figcaption>无向图邻接表：顶点表定长数组 + 每个顶点的邻接边单链表</figcaption>
</figure>

无向图中每条边会在两个顶点的链表中各出现一次，故 $e$ 条边共需 $2e$ 个边结点，空间为 $O(n+2e)$（数量级 $O(n+e)$）；有向图只存出边，$e$ 个边结点，空间 $O(n+e)$。

特点与操作：

- **度**：无向图中数该顶点单链表的边结点个数即可；有向图的邻接表（出边表）只能直接求**出度**，求入度需遍历全部边结点。若改为按入边建立的**逆邻接表**，则入度易求、出度难求。
- **邻接表不唯一**：边结点的顺序取决于建表时用头插法还是尾插法，与顶点编号无关；邻接矩阵则唯一。
- **与邻接矩阵的关系**：第 $i$ 个单链表对应矩阵第 $i$ 行，链表中边结点个数等于该行非零元素个数。
- **缺点**：判断任意两点之间是否有边不方便，需扫描相关链表。

建表算法（头插法）：输入顶点数、边数 → 建顶点表，`data` 填入顶点、`firstarc` 置空 → 循环每条边，输入两个端点并查其在顶点表中的下标 $i,j$，申请边结点（`adjvex=j`），头插到 $i$ 的单链表；无向图再申请一个 `adjvex=i` 的结点头插到 $j$ 的单链表。

**示例**：无向图 $V=\{A,B,C\}$，$E=\{AB,AC,BC\}$ 的邻接表：

| 顶点 | 单链表（邻接点） |
|:---:|:---|
| A | B → C |
| B | A → C |
| C | A → B |

有向图 $A\to B,A\to C,B\to C$ 的邻接表只存出边：A: B→C；B: C；C: 空。求入度需另建逆邻接表。

> **交互演示**：[邻接矩阵与邻接表](/lab/chapter-7/#lab-adjMatrix)

### 十字链表与邻接多重表

**十字链表**用于存储**有向图**，把邻接表与逆邻接表结合起来，解决“求出入度不能兼顾”的问题。

- **顶点结点**：`data`、`firstin`（以该顶点为弧头的第一条弧）、`firstout`（以该顶点为弧尾的第一条弧）。
- **弧结点**：`tailvex`（弧尾下标）、`headvex`（弧头下标）、`hlink`（下一条同弧头的弧）、`tlink`（下一条同弧尾的弧），网再加 `info`。

<figure class="cpd-figure not-content" id="wz-w4-fig-6">
  <svg viewBox="0 0 680 228" role="img" aria-labelledby="wz-fig-21">
    <title id="wz-fig-21">有向图十字链表结点结构：顶点结点与弧结点</title>
    <text class="fig-muted" x="30" y="20" font-size="12">十字链表 = 有向图邻接表（出边） + 逆邻接表（入边）</text>
    <text class="fig-title" x="30" y="46" font-size="12.5">顶点结点（每个顶点 1 个，共 3 域）</text>
    <rect class="fig-box" x="30" y="56" width="294" height="38" rx="4"/>
    <g class="fig-divider">
      <line x1="128" y1="56" x2="128" y2="94"/>
      <line x1="226" y1="56" x2="226" y2="94"/>
    </g>
    <g font-size="12.5" text-anchor="middle">
      <text class="fig-label" x="79" y="80">data</text>
      <text class="fig-blue" x="177" y="80">firstin</text>
      <text class="fig-accent" x="275" y="80">firstout</text>
    </g>
    <text class="fig-title" x="30" y="122" font-size="12.5">弧结点（每条弧 1 个，共 5 域）</text>
    <rect class="fig-box" x="30" y="132" width="480" height="38" rx="4"/>
    <g class="fig-divider">
      <line x1="126" y1="132" x2="126" y2="170"/>
      <line x1="222" y1="132" x2="222" y2="170"/>
      <line x1="318" y1="132" x2="318" y2="170"/>
      <line x1="414" y1="132" x2="414" y2="170"/>
    </g>
    <g font-size="12.5" text-anchor="middle">
      <text class="fig-label" x="78" y="156">tailvex</text>
      <text class="fig-label" x="174" y="156">headvex</text>
      <text class="fig-blue" x="270" y="156">hlink</text>
      <text class="fig-accent" x="366" y="156">tlink</text>
      <text class="fig-muted" x="462" y="156">info</text>
    </g>
    <g class="fig-muted" font-size="11.5">
      <text x="30" y="192">入度链（蓝）：firstin → 同弧头下一条弧 hlink</text>
      <text x="30" y="210">出度链（靛）：firstout → 同弧尾下一条弧 tlink（一次建表即可兼顾出度与入度）</text>
    </g>
  </svg>
  <figcaption>十字链表结点字段布局：同时串联同弧头入边链与同弧尾出边链</figcaption>
</figure>

这样沿 `firstout`/`tlink` 可数出出度，沿 `firstin`/`hlink` 可数出入度，两个方向都方便。

**邻接多重表**用于存储**无向图**，解决邻接表中每条边存两遍的问题——每条边只设一个边结点：

- **顶点结点**：`data`、`firstedge`（指向第一条依附于该顶点的边）。
- **边结点**：`ivex`、`jvex`（该边两个端点在顶点表中的下标）、`ilink`（依附于 `ivex` 的下一条边）、`jlink`（依附于 `jvex` 的下一条边）；可加 `mark`（是否被访问/搜索过）和权值域。

删除一条边只需找到并删除一个边结点，不必像邻接表那样处理两处；缺点是指针域多、结构较复杂。邻接多重表中的边结点次序同样不唯一。

<figure class="cpd-figure not-content" id="wz-w4-fig-10">
  <svg viewBox="0 0 700 256" role="img" aria-labelledby="wz-w4-fig-10-title">
    <title id="wz-w4-fig-10-title">无向图邻接多重表指针连线实例</title>
    <defs>
      <marker id="wz-w4-arr-10" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <text class="fig-title" x="95" y="22" text-anchor="middle" font-size="12.5">原无向图（3 边）</text>
    <text class="fig-title" x="430" y="22" text-anchor="middle" font-size="12.5">邻接多重表（每条边仅 1 个边结点：ivex | ilink | jvex | jlink）</text>
    <g class="fig-line">
      <line x1="95" y1="62" x2="45" y2="142"/>
      <line x1="95" y1="62" x2="145" y2="142"/>
      <line x1="45" y1="142" x2="145" y2="142"/>
    </g>
    <g class="fig-box-blue">
      <circle cx="95" cy="62" r="14"/><circle cx="45" cy="142" r="14"/><circle cx="145" cy="142" r="14"/>
    </g>
    <g class="fig-blue" font-size="11.5" text-anchor="middle">
      <text x="95" y="66">0</text><text x="45" y="146">1</text><text x="145" y="146">2</text>
    </g>
    <g class="fig-muted" font-size="10.5" text-anchor="middle">
      <text x="58" y="96">e₀</text><text x="132" y="96">e₁</text><text x="95" y="158">e₂</text>
    </g>
    <text class="fig-muted" x="235" y="46" text-anchor="middle" font-size="11">顶点表（data | firstedge）</text>
    <g class="fig-box">
      <rect x="190" y="56" width="90" height="32" rx="4"/>
      <rect x="190" y="106" width="90" height="32" rx="4"/>
      <rect x="190" y="156" width="90" height="32" rx="4"/>
    </g>
    <g class="fig-divider">
      <line x1="235" y1="56" x2="235" y2="88"/>
      <line x1="235" y1="106" x2="235" y2="138"/>
      <line x1="235" y1="156" x2="235" y2="188"/>
    </g>
    <g font-size="11.5" text-anchor="middle">
      <text class="fig-label" x="212" y="76">0 | v₁</text><circle class="fig-dot" cx="258" cy="72" r="3"/>
      <text class="fig-label" x="212" y="126">1 | v₂</text><circle class="fig-dot" cx="258" cy="122" r="3"/>
      <text class="fig-label" x="212" y="176">2 | v₃</text><circle class="fig-dot" cx="258" cy="172" r="3"/>
    </g>
    <g stroke="var(--sl-color-blue)" stroke-width="1.4" fill="none" marker-end="url(#wz-w4-arr-10)">
      <line x1="262" y1="72" x2="345" y2="72"/>
      <path d="M 424 72 L 456 72 L 456 122 L 502 122"/>
      <line x1="262" y1="122" x2="502" y2="122"/>
    </g>
    <g stroke="var(--sl-color-accent)" stroke-width="1.4" fill="none" marker-end="url(#wz-w4-arr-10)">
      <path d="M 480 88 L 480 172 L 502 172"/>
      <path d="M 262 172 L 320 172 L 320 202 L 634 202 L 634 142"/>
    </g>
    <g class="fig-box-blue">
      <rect x="350" y="56" width="144" height="32" rx="4"/>
      <rect x="508" y="106" width="144" height="32" rx="4"/>
      <rect x="508" y="156" width="144" height="32" rx="4"/>
    </g>
    <g class="fig-divider">
      <line x1="386" y1="56" x2="386" y2="88"/><line x1="422" y1="56" x2="422" y2="88"/><line x1="458" y1="56" x2="458" y2="88"/>
      <line x1="544" y1="106" x2="544" y2="138"/><line x1="580" y1="106" x2="580" y2="138"/><line x1="616" y1="106" x2="616" y2="138"/>
      <line x1="544" y1="156" x2="544" y2="188"/><line x1="580" y1="156" x2="580" y2="188"/><line x1="616" y1="156" x2="616" y2="188"/>
    </g>
    <g font-size="11" text-anchor="middle">
      <text class="fig-muted" x="422" y="46">边结点 e₀(0,1)</text>
      <text class="fig-blue" x="368" y="76">0</text><text class="fig-blue" x="404" y="76">ilink</text><text class="fig-accent" x="440" y="76">1</text><text class="fig-accent" x="476" y="76">jlink</text>
      <text class="fig-muted" x="580" y="96">边结点 e₁(0,2)</text>
      <text class="fig-blue" x="526" y="126">0</text><text class="fig-muted" x="562" y="126">∧</text><text class="fig-accent" x="598" y="126">2</text><text class="fig-muted" x="634" y="126">∧</text>
      <text class="fig-muted" x="580" y="148">边结点 e₂(1,2)</text>
      <text class="fig-blue" x="526" y="176">1</text><text class="fig-muted" x="562" y="176">∧</text><text class="fig-accent" x="598" y="176">2</text><text class="fig-muted" x="634" y="176">∧</text>
    </g>
    <text class="fig-muted" x="350" y="236" text-anchor="middle" font-size="11">蓝线沿 ilink 串联依附 ivex 的边，靛线沿 jlink 串联依附 jvex 的边；删边 e₀ 只需删 1 个边结点</text>
  </svg>
  <figcaption>无向图邻接多重表实例：每条边只设 1 个边结点，通过 ilink 与 jlink 同时挂入两个端点的边链</figcaption>
</figure>

| 存储结构 | 适用对象 | 空间 | 求度 | 删除边 |
| --- | --- | --- | --- | --- |
| 邻接矩阵 | 任意图/网 | $O(n^2)$ | 无向行和；有向行和=出度、列和=入度 | 麻烦，需增删行列 |
| 邻接表 | 任意图/网 | $O(n+e)$（无向 $2e$ 个边结点） | 无向易；有向仅出度易 | 无向需删两个结点 |
| 十字链表 | 有向图 | $O(n+e)$ | 出度、入度都易 | 方便 |
| 邻接多重表 | 无向图 | $O(n+e)$ | 沿依附链找边方便 | 只删一个结点，方便 |

### 深度优先搜索（DFS）思想

**图的遍历**：从图中某一顶点出发，沿边访问所有顶点，且**每个顶点只访问一次**。为避免重复访问和回路造成的死循环，设辅助数组 `visited[n]`，初值全 $0$，访问后置 $1$。

**深度优先搜索（DFS）**：访问起点 $v$ 后，任选一个未访问的邻接点 $w$ 深入；再从 $w$ 出发选其未访问邻接点继续深入。**只要还能往前走就一直走（“一条道走到黑”）**；走不通时退回上一个访问过的顶点，若它还有未访问的邻接点则继续深入，否则再回退，直到所有顶点被访问。

- 本质：找到当前顶点的邻接点，依次访问，能深则深。
- 与树的**先根遍历**相似：先访问根，再深入子树，走不动才回溯。
- 当某顶点有多个未访问邻接点时**任选其一**，因此同一张图的 DFS 序列可以有多种；但一旦存储结构和算法确定，遍历序列就确定了。

### DFS 的实现与复杂度

邻接矩阵上的递归实现：

```c
void DFS(AMGraph G, int v) {
    printf("%d", v);
    visited[v] = 1;                      // 访问并标记
    for (int w = 0; w < G.vexnum; w++)   // 扫描 v 所在的一行
        if (G.arcs[v][w] && !visited[w]) // 有边且未访问
            DFS(G, w);                   // 递归深入
}
```

- 邻接矩阵中找邻接点的条件：元素非零（网为“非 $\infty$”）且 `visited[w]==0`。
- 非连通图需在外层对每个顶点检查一次：

```c
for (int v = 0; v < G.vexnum; v++)
    if (!visited[v]) DFS(G, v);   // 每调用一次得到一个连通分量
```

改用邻接表时，把“扫描一行”换成“沿 `firstarc` 遍历该顶点的边链表”，其余不变。

| 存储结构 | 时间复杂度 | 空间复杂度 | 说明 |
| --- | --- | --- | --- |
| 邻接矩阵 | $O(n^2)$ | $O(n)$ | 每个顶点都要扫描长度为 $n$ 的一行，与边数无关 |
| 邻接表 | $O(n+e)$ | $O(n)$ | 访问 $n$ 个头结点 + 扫描 $e$ 个边结点（无向图 $2e$） |

空间开销来自递归工作栈，最坏情况（近似单链）深度为 $n$，故为 $O(n)$。

> **★考点**：DFS 时间复杂度只与**存储结构**有关，与遍历顺序无关；稠密图用邻接矩阵，稀疏图用邻接表。

### 广度优先搜索（BFS）

**广度优先搜索**：从起点 $v$ 出发，先依次访问 $v$ 的**所有邻接点**；再按这些邻接点被访问的先后次序，依次访问它们的未访问邻接点；如此一层一层向外扩展，直到所有顶点访问完。类似树的**层次遍历**，用**队列**实现，是非递归算法。

```c
void BFS(Graph G, int v) {
    visit(v); visited[v] = 1;
    InitQueue(Q); EnQueue(Q, v);          // 起点入队
    while (!QueueEmpty(Q)) {
        DeQueue(Q, u);                    // 出队一个顶点
        for (每个未访问的邻接点 w of u) {
            visit(w); visited[w] = 1;
            EnQueue(Q, w);                // 邻接点依次入队
        }
    }
}
```

- 出队顺序就是顶点的访问顺序；已访问的邻接点不再入队。
- 非连通图同样在外层对未访问顶点再调用 BFS；调用次数等于连通分量数。
- 空间复杂度 $O(n)$（队列最坏存放全部顶点）；时间复杂度与 DFS 相同：邻接矩阵 $O(n^2)$，邻接表 $O(n+e)$。

> **★考点**：DFS 与 BFS 的时间复杂度只取决于存储结构，空间复杂度都为 $O(n)$；BFS 需队列，DFS 需栈（递归即系统栈）。

一个典型应用是**六度空间理论**（小世界理论）的验证：把人抽象为顶点、认识关系抽象为无向边，从任一顶点做 BFS，统计路径长度不超过 7 的顶点占比，若达到 90% 以上即认为理论成立。

<figure class="cpd-figure not-content" id="wz-w4-fig-11">
  <svg viewBox="0 0 700 292" role="img" aria-labelledby="wz-w4-fig-11-title">
    <title id="wz-w4-fig-11-title">深度优先搜索（DFS）与广度优先搜索（BFS）过程及生成树对比</title>
    <defs>
      <marker id="wz-w4-arr-11" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <text class="fig-title" x="175" y="22" text-anchor="middle" font-size="12.5">DFS：一条道走到黑（递归 / 栈）</text>
    <text class="fig-title" x="525" y="22" text-anchor="middle" font-size="12.5">BFS：按层向外扩展（队列）</text>
    <line class="fig-divider" x1="350" y1="16" x2="350" y2="276"/>
    <line class="fig-line-dashed" x1="175" y1="54" x2="235" y2="108"/>
    <g stroke="var(--sl-color-accent)" stroke-width="2" fill="none" marker-end="url(#wz-w4-arr-11)">
      <line x1="164" y1="64" x2="124" y2="96"/>
      <line x1="106" y1="122" x2="78" y2="160"/>
      <line x1="124" y1="120" x2="156" y2="160"/>
      <line x1="180" y1="166" x2="224" y2="120"/>
    </g>
    <g class="fig-box-accent">
      <circle cx="175" cy="54" r="14"/><circle cx="115" cy="108" r="14"/><circle cx="68" cy="172" r="14"/>
      <circle cx="168" cy="172" r="14"/><circle cx="235" cy="108" r="14"/>
    </g>
    <g class="fig-accent" font-size="11.5" text-anchor="middle">
      <text x="175" y="58">v₀</text><text x="115" y="112">v₁</text><text x="68" y="176">v₃</text>
      <text x="168" y="176">v₄</text><text x="235" y="112">v₂</text>
    </g>
    <g class="fig-muted" font-size="10" text-anchor="middle">
      <text x="198" y="54">①</text><text x="90" y="112">②</text><text x="44" y="176">③</text>
      <text x="192" y="176">④</text><text x="258" y="112">⑤</text>
    </g>
    <rect class="fig-box-subtle" x="28" y="204" width="294" height="62" rx="5"/>
    <g font-size="11">
      <text class="fig-label" x="40" y="224">访问序列：v₀ → v₁ → v₃ → (回溯 v₁) → v₄ → v₂</text>
      <text class="fig-muted" x="40" y="242">系统栈深：v₀→v₁→v₃ 达最大深度，回溯后走 v₄→v₂</text>
      <text class="fig-muted" x="40" y="258">实线为 DFS 生成树边，虚线 (v₀,v₂) 为回边</text>
    </g>
    <line class="fig-line-dashed" x1="585" y1="108" x2="528" y2="172"/>
    <g stroke="var(--sl-color-blue)" stroke-width="2" fill="none" marker-end="url(#wz-w4-arr-11)">
      <line x1="514" y1="64" x2="474" y2="96"/>
      <line x1="536" y1="64" x2="576" y2="96"/>
      <line x1="456" y1="122" x2="428" y2="160"/>
      <line x1="474" y1="120" x2="506" y2="160"/>
    </g>
    <g class="fig-box-blue">
      <circle cx="525" cy="54" r="14"/><circle cx="465" cy="108" r="14"/><circle cx="585" cy="108" r="14"/>
      <circle cx="418" cy="172" r="14"/><circle cx="518" cy="172" r="14"/>
    </g>
    <g class="fig-blue" font-size="11.5" text-anchor="middle">
      <text x="525" y="58">v₀</text><text x="465" y="112">v₁</text><text x="585" y="112">v₂</text>
      <text x="418" y="176">v₃</text><text x="518" y="176">v₄</text>
    </g>
    <g class="fig-muted" font-size="10" text-anchor="middle">
      <text x="548" y="54">①</text><text x="440" y="112">②</text><text x="608" y="112">③</text>
      <text x="394" y="176">④</text><text x="542" y="176">⑤</text>
    </g>
    <rect class="fig-box-subtle" x="378" y="204" width="294" height="62" rx="5"/>
    <g font-size="11">
      <text class="fig-label" x="390" y="224">访问序列：v₀ → v₁ → v₂ → v₃ → v₄</text>
      <text class="fig-muted" x="390" y="242" font-size="9.2">队列变化：[v₀] → [v₁,v₂] → [v₂,v₃,v₄] → [v₃,v₄] → []</text>
      <text class="fig-muted" x="390" y="258">实线为 BFS 生成树边，虚线 (v₂,v₄) 为非树边</text>
    </g>
  </svg>
  <figcaption>DFS 与 BFS 遍历过程及生成树对比：同一张图从 v₀ 出发分别得到深度优先生成树与广度优先生成树</figcaption>
</figure>

> **交互演示**：[图的深度优先 DFS 与广度优先 BFS](/lab/chapter-7/#lab-dfs)

### 生成树与极小连通子图

连通图的**生成树**：包含图中全部 $n$ 个顶点，但只含 $n-1$ 条边，且连通、无回路。它是图的**极小连通子图**——边少到不能再少（再删一条边就不连通），也多不了（再加一条边必成回路）。

三条性质：

1. 顶点数与图相同（$n$ 个）；边数恰为 $n-1$。
2. 生成树中任意两顶点间的路径**唯一**。
3. 一个连通图的生成树**不唯一**（同一组顶点可取不同的 $n-1$ 条边）。

> **注意**：$n$ 个顶点、$n-1$ 条边的图**不一定**是生成树。反例：5 个顶点 4 条边，但分成两个连通分量（不连通），或其中含回路——都不满足定义。

**构造方法**：对图做一次遍历，把遍历经过的边收集起来，加上全部顶点即得生成树。

- 用 DFS 得到**深度优先生成树**（一条路走到底，回溯时不再收边）；
- 用 BFS 得到**广度优先生成树**（按层扩张，每个顶点由第一次发现它的边接入）。

遍历把边集分成两部分：经过的边（记 $T$）与未经过的边；$T$ 加全部顶点就是生成树。两种生成树一般不唯一，取决于起点与邻接点的访问次序。

### 最小生成树与 MST 性质

**最小生成树**（MST，Minimum Spanning Tree，又称最小代价生成树）：在无向网的全部生成树中，**各边权值之和最小**的那一棵。

同一张网的不同生成树权值和不同（课程例子中两棵生成树权值和分别为 19 与 17），MST 取其中最小者。

**典型应用**：$n$ 个城市建通信网、$n$ 个村庄修公路。要求连通 → 至少 $n-1$ 条线路；要求总造价最低 → 选 $n-1$ 条权值（造价）之和最小的边。抽象成无向连通网后，问题就是求 MST。

**MST 性质**（构造一切 MST 算法的依据）：设 $N=(V,E)$ 是连通网，$U$ 是 $V$ 的非空子集。若 $(u,v)$ 是所有「一端在 $U$、另一端在 $V-U$」的边中**权值最小**的边，则必存在一棵包含边 $(u,v)$ 的最小生成树。

理解方式：已选入生成树的顶点构成 $U$，未选入的构成 $V-U$；下一步只需在跨越这个割的边里挑权值最小者，这个贪心选择不会错过最优解（教材用反证法证明）。若选中的边会造成回路，则舍弃，改取次小者。

<figure class="cpd-figure not-content" id="wz-w4-fig-7">
  <svg viewBox="0 0 680 280" role="img" aria-labelledby="wz-fig-22">
    <title id="wz-fig-22">最小生成树（MST）性质的割边选择示意</title>
    <line class="fig-line-dashed" x1="296" y1="22" x2="296" y2="262"/>
    <text class="fig-muted" x="308" y="34" font-size="12">割 (U, V − U)</text>
    <g class="fig-line">
      <line x1="158" y1="138" x2="438" y2="56"/>
      <line x1="158" y1="146" x2="438" y2="224"/>
    </g>
    <line stroke="var(--sl-color-accent)" stroke-width="2.6" x1="158" y1="142" x2="466" y2="142"/>
    <g class="fig-line-dashed">
      <line x1="440" y1="62" x2="464" y2="136"/>
      <line x1="464" y1="148" x2="440" y2="218"/>
    </g>
    <circle class="fig-box-blue" cx="142" cy="142" r="18"/>
    <g class="fig-box">
      <circle cx="440" cy="56" r="17"/>
      <circle cx="440" cy="224" r="17"/>
    </g>
    <circle class="fig-box-accent" cx="468" cy="142" r="17"/>
    <g font-size="12.5" text-anchor="middle">
      <text class="fig-blue" x="142" y="147">v₁</text>
      <text class="fig-muted" x="142" y="180" font-size="11.5">u ∈ U</text>
      <text class="fig-label" x="440" y="61">v₂</text>
      <text class="fig-accent" x="468" y="147">v₃</text>
      <text class="fig-label" x="440" y="229">v₄</text>
    </g>
    <g font-size="12" text-anchor="middle">
      <text class="fig-muted" x="272" y="92">6</text>
      <rect x="174" y="117" width="98" height="18" rx="3" fill="var(--sl-color-bg)" stroke="none"/>
      <text class="fig-accent" x="223" y="130">1（跨割最小边）</text>
      <text class="fig-muted" x="272" y="198">5</text>
      <text class="fig-muted" x="438" y="104">5</text>
      <text class="fig-muted" x="438" y="186">5</text>
    </g>
    <text class="fig-muted" x="440" y="262" text-anchor="middle" font-size="11.5">v₂, v₃, v₄ ∈ V − U；必存在包含最小跨割边 (v₁, v₃) 的 MST</text>
  </svg>
  <figcaption>MST 性质：连接已选集 U 与未选集 V − U 的最小权边必可安全加入生成树</figcaption>
</figure>

### Prim 算法（普里姆）

**思想：以顶点为单位的扩张**。从任一顶点（通常取序号最小者）开始，把它放进已选顶点集 $U$，边集 $TE$ 置空；每一轮在「$U$ 到 $V-U$」的所有边中选**权值最小**的边 $(u_0,v_0)$，把 $v_0$ 并入 $U$、把该边并入 $TE$；重复至 $U=V$，此时 $|TE|=n-1$。

步骤：

1. $U=\{v_1\}$，$TE=\varnothing$。
2. 在 $\{(u,v)\mid u\in U,\ v\in V-U\}$ 中取权最小的边 $(u_0,v_0)$。
3. $U=U\cup\{v_0\}$，$TE=TE\cup\{(u_0,v_0)\}$。
4. 若 $|U|<n$ 转步骤 2；否则 $TE$ 即最小生成树的边集。

特点与代价：

- 每轮只并入**一个顶点、一条边**，天然不会产生回路。
- 时间复杂度 $O(n^2)$：每个顶点都要与其余顶点比较判断，与边数无关。
- 因此**适合稠密图**（边多、$e$ 接近 $n^2$）。
- 课程说明：两种 MST 算法的代码实现不作要求，掌握思想与复杂度即可。

### Kruskal 算法（克鲁斯卡尔）

**思想：以边为单位的贪心**。把全部 $n$ 个顶点先放进生成树（初始无边，每个顶点自成一个连通分量），把全部边**按权值升序排序**，依次扫描：若该边的两个端点属于**不同连通分量**（加入后不构成回路），则加入 $TE$；否则舍弃。直到 $|TE|=n-1$（或所有顶点连通）为止。

步骤：

1. $TE=\varnothing$，$n$ 个顶点各自为一个连通分量。
2. 对 $E$ 按权值非降序排序。
3. 依次取边 $(u,v)$：若 $u,v$ 分属不同连通分量，加入 $TE$ 并合并两个分量；否则丢弃。
4. 当 $|TE|=n-1$ 时结束。

特点与代价：

- 直截了当的贪心，不需要指定起点。
- 判环依靠「两端点是否在同一连通分量」（实现上用并查集）。
- 时间复杂度 $O(e\log e)$：主要是排序开销，与顶点数无关。
- 因此**适合稀疏图**（顶点多、边少）。

### Prim 与 Kruskal 的对比、MST 的唯一性

| 比较项 | Prim | Kruskal |
| --- | --- | --- |
| 每次操作 | 选一个顶点（连一条最小割边） | 选一条边（全局最小且不成环） |
| 扩张方式 | $U$ 从单点逐步长大 | 森林逐步合并成树 |
| 时间复杂度 | $O(n^2)$ | $O(e\log e)$ |
| 与谁相关 | 只与顶点数有关 | 只与边数有关 |
| 适用图 | 稠密图 | 稀疏图 |
| 终止条件 | $U=V$ | $\lvert TE\rvert=n-1$ |

> **注意**：**最小生成树不一定唯一**。当网中存在权值相等的边时，不同的选择会得到不同的 MST，但最小权值和相同。例如把某条权为 6 的边改为 5 后，选它或不选它都能构造出权值和相等的两棵生成树。

<figure class="cpd-figure not-content" id="wz-w4-fig-12">
  <svg viewBox="0 0 700 320" role="img" aria-labelledby="wz-w4-fig-12-title">
    <title id="wz-w4-fig-12-title">Prim 算法与 Kruskal 算法构建最小生成树逐步演进对比</title>
    <defs>
      <marker id="wz-w4-arr-12" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <text class="fig-title" x="350" y="22" text-anchor="middle" font-size="12.5">Prim（按顶点集 U 扩张） vs Kruskal（按边权排序 + 并查集判环）</text>
    <text class="fig-blue" x="22" y="48" font-size="11.5">Prim 演进（从 A 出发）</text>
    <text class="fig-muted" x="180" y="48" font-size="11">每轮取连接 U 与 V−U 的最小权边</text>
    <g class="fig-line-dashed">
      <line x1="48" y1="74" x2="120" y2="74"/><line x1="120" y1="74" x2="120" y2="126"/>
      <line x1="48" y1="74" x2="120" y2="126"/><line x1="120" y1="126" x2="48" y2="126"/><line x1="120" y1="74" x2="48" y2="126"/>
      <line x1="210" y1="74" x2="282" y2="126"/><line x1="282" y1="126" x2="210" y2="126"/><line x1="282" y1="74" x2="210" y2="126"/>
      <line x1="372" y1="74" x2="444" y2="126"/><line x1="444" y1="126" x2="372" y2="126"/><line x1="444" y1="74" x2="372" y2="126"/>
      <line x1="534" y1="74" x2="606" y2="126"/><line x1="606" y1="74" x2="534" y2="126"/>
    </g>
    <g class="fig-line-accent">
      <line x1="210" y1="74" x2="282" y2="74"/>
      <line x1="372" y1="74" x2="444" y2="74"/><line x1="444" y1="74" x2="444" y2="126"/>
      <line x1="534" y1="74" x2="606" y2="74"/><line x1="606" y1="74" x2="606" y2="126"/><line x1="606" y1="126" x2="534" y2="126"/>
    </g>
    <g class="fig-line" marker-end="url(#wz-w4-arr-12)">
      <line x1="146" y1="100" x2="184" y2="100"/>
      <line x1="308" y1="100" x2="346" y2="100"/>
      <line x1="470" y1="100" x2="508" y2="100"/>
    </g>
    <g class="fig-box">
      <circle cx="120" cy="74" r="11"/><circle cx="120" cy="126" r="11"/><circle cx="48" cy="126" r="11"/>
      <circle cx="282" cy="126" r="11"/><circle cx="210" cy="126" r="11"/>
      <circle cx="372" cy="126" r="11"/>
    </g>
    <g class="fig-box-blue">
      <circle cx="48" cy="74" r="11"/>
      <circle cx="210" cy="74" r="11"/><circle cx="282" cy="74" r="11"/>
      <circle cx="372" cy="74" r="11"/><circle cx="444" cy="74" r="11"/><circle cx="444" cy="126" r="11"/>
      <circle cx="534" cy="74" r="11"/><circle cx="606" cy="74" r="11"/><circle cx="606" cy="126" r="11"/><circle cx="534" cy="126" r="11"/>
    </g>
    <g font-size="10.5" text-anchor="middle">
      <text class="fig-blue" x="48" y="78">A</text><text class="fig-label" x="120" y="78">B</text><text class="fig-label" x="120" y="130">C</text><text class="fig-label" x="48" y="130">D</text>
      <text class="fig-blue" x="210" y="78">A</text><text class="fig-blue" x="282" y="78">B</text><text class="fig-label" x="282" y="130">C</text><text class="fig-label" x="210" y="130">D</text>
      <text class="fig-blue" x="372" y="78">A</text><text class="fig-blue" x="444" y="78">B</text><text class="fig-blue" x="444" y="130">C</text><text class="fig-label" x="372" y="130">D</text>
      <text class="fig-blue" x="534" y="78">A</text><text class="fig-blue" x="606" y="78">B</text><text class="fig-blue" x="606" y="130">C</text><text class="fig-blue" x="534" y="130">D</text>
    </g>
    <g class="fig-muted" font-size="10.5" text-anchor="middle">
      <text x="84" y="154">初始 U=&#123;A&#125;</text>
      <text x="246" y="154">并入 B（边权 1）</text>
      <text x="408" y="154">并入 C（边权 2）</text>
      <text x="570" y="154">并入 D（边权 4）</text>
    </g>
    <line class="fig-divider" x1="20" y1="172" x2="680" y2="172"/>
    <text class="fig-green" x="22" y="194" font-size="11.5">Kruskal 演进（按边升序）</text>
    <text class="fig-muted" x="195" y="194" font-size="11">排序：(A,B):1 → (B,C):2 → (A,C):3 → (C,D):4 → (B,D):5</text>
    <g class="fig-line-dashed">
      <line x1="48" y1="220" x2="120" y2="272"/><line x1="120" y1="220" x2="48" y2="272"/>
      <line x1="120" y1="220" x2="120" y2="272"/><line x1="120" y1="272" x2="48" y2="272"/>
      <line x1="210" y1="220" x2="282" y2="272"/><line x1="282" y1="272" x2="210" y2="272"/><line x1="282" y1="220" x2="210" y2="272"/>
      <line x1="372" y1="220" x2="444" y2="272"/><line x1="444" y1="272" x2="372" y2="272"/><line x1="444" y1="220" x2="372" y2="272"/>
      <line x1="534" y1="220" x2="606" y2="272"/><line x1="606" y1="220" x2="534" y2="272"/>
    </g>
    <g class="fig-line-green">
      <line x1="48" y1="220" x2="120" y2="220"/>
      <line x1="210" y1="220" x2="282" y2="220"/><line x1="282" y1="220" x2="282" y2="272"/>
      <line x1="372" y1="220" x2="444" y2="220"/><line x1="444" y1="220" x2="444" y2="272"/>
      <line x1="534" y1="220" x2="606" y2="220"/><line x1="606" y1="220" x2="606" y2="272"/><line x1="606" y1="272" x2="534" y2="272"/>
    </g>
    <line stroke="var(--sl-color-red)" stroke-width="1.8" stroke-dasharray="3 2" x1="372" y1="220" x2="444" y2="272"/>
    <g class="fig-line" marker-end="url(#wz-w4-arr-12)">
      <line x1="146" y1="246" x2="184" y2="246"/>
      <line x1="308" y1="246" x2="346" y2="246"/>
      <line x1="470" y1="246" x2="508" y2="246"/>
    </g>
    <g class="fig-box-green">
      <circle cx="48" cy="220" r="11"/><circle cx="120" cy="220" r="11"/><circle cx="120" cy="272" r="11"/><circle cx="48" cy="272" r="11"/>
      <circle cx="210" cy="220" r="11"/><circle cx="282" cy="220" r="11"/><circle cx="282" cy="272" r="11"/><circle cx="210" cy="272" r="11"/>
      <circle cx="372" cy="220" r="11"/><circle cx="444" cy="220" r="11"/><circle cx="444" cy="272" r="11"/><circle cx="372" cy="272" r="11"/>
      <circle cx="534" cy="220" r="11"/><circle cx="606" cy="220" r="11"/><circle cx="606" cy="272" r="11"/><circle cx="534" cy="272" r="11"/>
    </g>
    <g class="fig-green" font-size="10.5" text-anchor="middle">
      <text x="48" y="224">A</text><text x="120" y="224">B</text><text x="120" y="276">C</text><text x="48" y="276">D</text>
      <text x="210" y="224">A</text><text x="282" y="224">B</text><text x="282" y="276">C</text><text x="210" y="276">D</text>
      <text x="372" y="224">A</text><text x="444" y="224">B</text><text x="444" y="276">C</text><text x="372" y="276">D</text>
      <text x="534" y="224">A</text><text x="606" y="224">B</text><text x="606" y="276">C</text><text x="534" y="276">D</text>
    </g>
    <g class="fig-muted" font-size="10.5" text-anchor="middle">
      <text x="84" y="302">① 选 (A,B):1</text>
      <text x="246" y="302">② 选 (B,C):2</text>
      <text class="fig-red" x="408" y="302">③ (A,C):3 成环舍弃</text>
      <text x="570" y="302">④ 选 (C,D):4（总权 7）</text>
    </g>
  </svg>
  <figcaption>Prim 与 Kruskal 演进对比：Prim 每次扩展 1 个顶点天然无环，Kruskal 每次选全局最小边需并查集判环</figcaption>
</figure>

> **交互演示**：[最小生成树 Prim 与 Kruskal](/lab/chapter-7/#lab-prim)

### 最短路径问题的抽象

用**有向网**描述交通网络：顶点 = 地点，弧 = 两地间的通路，弧上的权 = 距离 / 时间 / 费用。求「从起点到终点怎么走最省」，就抽象为**最短路径**问题。

- **源点**（起点）：路径的出发点；**终点**：路径的到达点。
- 最短路径：源点到终点的所有路径中，**各边权值之和最小**的那条。

两类问题：

1. **单源最短路径**：求源点到其余各顶点的最短路径 → **Dijkstra 算法**。
2. **每对顶点之间的最短路径**：求任意两顶点间的最短路径 → **Floyd 算法**（也可对每个顶点各跑一次 Dijkstra，$n\cdot O(n^2)=O(n^3)$）。

> **注意**：最短路径与最小生成树是两类问题。最短路径**不要求包含全部顶点**，也不要求 $n-1$ 条边；只要从源点能到达终点，且边权之和最小。例如 $v_1\to v_7$ 有两条路径，长度分别为 20 与 14，答案取 14。

> **★考点**：只求某**一个**源点到**某一个**终点的最短路径，仍要跑完整的 Dijkstra，并不会比求到所有顶点更简单。

### Dijkstra 算法（迪杰斯特拉）

按**路径长度递增**的次序，逐个确定源点到各顶点的最短路径。

- 集合 $S$：已确定最短路径的顶点；$T=V-S$：尚未确定者。初始 $S=\{v_0\}$。
- 数组 $dist[i]$：当前源点到 $v_i$ 的最短距离。初值取直达弧的权；无直达弧记 $\infty$。

步骤：

1. 初始化 $S=\{v_0\}$，$dist[i]=w(v_0,v_i)$（无弧则 $\infty$）。
2. 在 $T$ 中取 $dist$ 最小的顶点 $u$，将其并入 $S$——此时 $dist[u]$ 就是 $v_0$ 到 $u$ 的最短距离。
3. 以 $u$ 为中转**松弛**：对 $T$ 中每个与 $u$ 相邻的 $v$，若 $dist[u]+w(u,v)<dist[v]$，则更新 $dist[v]$（并记下前驱，用于回溯路径）。
4. 重复 2、3，直到 $T=\varnothing$。

**算例**（源点 $v_0$，$\infty$ 表示暂不可达）：

| 轮次 | 并入 $S$ | $dist[v_1]$ | $dist[v_2]$ | $dist[v_3]$ | $dist[v_4]$ | $dist[v_5]$ | $dist[v_6]$ |
| --- | --- | --- | --- | --- | --- | --- | --- |
| 初始（直达） | — | 13 | 8 | $\infty$ | 30 | $\infty$ | 32 |
| 1 | $v_2$（8） | 13 | 8 | 13 | 30 | $\infty$ | 32 |
| 2 | $v_1$（13） | 13 | 8 | 13 | 30 | 22 | 20 |
| 3 | $v_3$（13） | 13 | 8 | 13 | 19 | 22 | 20 |
| 4 | $v_4$（19） | 13 | 8 | 13 | 19 | 21 | 20 |
| 5 | $v_6$（20） | 13 | 8 | 13 | 19 | 21 | 20 |
| 6 | $v_5$（21） | 13 | 8 | 13 | 19 | 21 | 20 |

关键松弛：$v_2\to v_3$ 得 $8+5=13$；$v_1\to v_5$ 得 $13+9=22$、$v_1\to v_6$ 得 $13+7=20$；$v_3\to v_4$ 得 $13+6=19$；$v_4\to v_5$ 得 $19+2=21$（比 22 更短）。最终路径：$v_3$ 经 $v_0\to v_2\to v_3$，$v_4$ 经 $v_0\to v_2\to v_3\to v_4$，$v_5$ 经 $v_0\to v_2\to v_3\to v_4\to v_5$，$v_6$ 经 $v_0\to v_1\to v_6$。

复杂度 $O(n^2)$（每轮选最小 + 松弛，各为 $O(n)$）。

> **注意**：该算法要求**边权非负**。按长度递增「一旦入 $S$ 即最终确定」的前提，依赖后续路径不会更短；若存在负权边，已确定的顶点仍可能被负权路径改写，算法失效（这类情形要用 Bellman-Ford 等算法，课程未涉及）。

<figure class="cpd-figure not-content" id="wz-w4-fig-13">
  <svg viewBox="0 0 700 294" role="img" aria-labelledby="wz-w4-fig-13-title">
    <title id="wz-w4-fig-13-title">Dijkstra 算法单源最短路径逐步松弛演进</title>
    <defs>
      <marker id="wz-w4-arr-13" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <text class="fig-title" x="155" y="22" text-anchor="middle" font-size="12.5">有向网与最终最短路径树（源点 v₀）</text>
    <text class="fig-title" x="505" y="22" text-anchor="middle" font-size="12.5">集合 S 扩张与 dist[] 关键松弛过程</text>
    <g stroke="var(--sl-color-gray-4)" stroke-width="1.3" fill="none" marker-end="url(#wz-w4-arr-13)">
      <line x1="60" y1="158" x2="188" y2="158"/>
      <line x1="56" y1="170" x2="150" y2="232"/>
      <line x1="128" y1="90" x2="218" y2="90"/>
    </g>
    <g stroke="var(--sl-color-accent)" stroke-width="2" fill="none" marker-end="url(#wz-w4-arr-13)">
      <line x1="56" y1="146" x2="104" y2="100"/>
      <line x1="56" y1="168" x2="104" y2="218"/>
      <line x1="128" y1="226" x2="190" y2="226"/>
      <line x1="204" y1="214" x2="204" y2="174"/>
      <line x1="216" y1="150" x2="256" y2="102"/>
      <line x1="124" y1="78" x2="156" y2="56"/>
    </g>
    <g class="fig-box-accent">
      <circle cx="46" cy="158" r="14"/><circle cx="114" cy="90" r="14"/><circle cx="114" cy="226" r="14"/>
      <circle cx="204" cy="226" r="14"/><circle cx="204" cy="158" r="14"/><circle cx="266" cy="90" r="14"/>
      <circle cx="168" cy="48" r="14"/>
    </g>
    <g class="fig-accent" font-size="11" text-anchor="middle">
      <text x="46" y="162">v₀</text><text x="114" y="94">v₁</text><text x="114" y="230">v₂</text>
      <text x="204" y="230">v₃</text><text x="204" y="162">v₄</text><text x="266" y="94">v₅</text>
      <text x="168" y="52">v₆</text>
    </g>
    <g font-size="10" text-anchor="middle">
      <text class="fig-accent" x="72" y="118">13</text>
      <text class="fig-accent" x="72" y="202">8</text>
      <text class="fig-accent" x="158" y="218">5</text>
      <text class="fig-accent" x="218" y="196">6</text>
      <text class="fig-accent" x="246" y="132">2</text>
      <text class="fig-accent" x="134" y="60">7</text>
      <text class="fig-muted" x="174" y="82">9</text>
      <text class="fig-muted" x="128" y="150">30</text>
      <text class="fig-muted" x="96" y="250">32 (v₀→v₆)</text>
    </g>
    <text class="fig-muted" x="155" y="274" text-anchor="middle" font-size="10.5">蓝线构成源点 v₀ 到各顶点的最短路径树</text>
    <g class="fig-box-subtle">
      <rect x="330" y="38" width="348" height="46" rx="5"/>
      <rect x="330" y="94" width="348" height="46" rx="5"/>
      <rect x="330" y="150" width="348" height="46" rx="5"/>
      <rect x="330" y="206" width="348" height="62" rx="5"/>
    </g>
    <g font-size="11">
      <text class="fig-label" x="342" y="56">初始 S=&#123;v₀&#125;（填入直达弧权）</text>
      <text class="fig-muted" x="342" y="74">dist = [v₁:13, v₂:8, v₃:∞, v₄:30, v₅:∞, v₆:32]</text>
      <text class="fig-blue" x="342" y="112">第 1 轮：选最小 v₂(8) 并入 S</text>
      <text class="fig-muted" x="342" y="130">松弛 v₂→v₃：dist[v₃] 由 ∞ → 8+5=13</text>
      <text class="fig-blue" x="342" y="168">第 2 轮：选 v₁(13) 并入 S</text>
      <text class="fig-muted" x="342" y="186">松弛 v₁→v₅, v₆：dist[v₅]→22，dist[v₆]: 32→20</text>
      <text class="fig-accent" x="342" y="224">第 3–4 轮：依次选 v₃(13)、v₄(19) 并入 S</text>
      <text class="fig-muted" x="342" y="242">v₃→v₄ 得 dist[v₄]: 30→19；v₄→v₅ 得 19+2=21 &lt; 22</text>
      <text class="fig-green" x="342" y="259">最终 dist = [13, 8, 13, 19, 21, 20]（第 5–6 轮定稿 v₆, v₅）</text>
    </g>
  </svg>
  <figcaption>Dijkstra 算法逐步松弛演进：每轮在 T=V−S 中选 dist 最小者并入 S，再以它为中转松弛邻接点</figcaption>
</figure>

### Floyd 算法（弗洛伊德）

求**每一对顶点之间**的最短路径。用 $n$ 阶方阵 $A$ 记录任意两顶点间的当前最短路径长度：初始即邻接矩阵（$A[i][i]=0$；有弧取弧权；无弧取 $\infty$）。

思想：**逐个把顶点当作中间点试探**。第 $k$ 轮允许路径经过 $v_k$ 中转，若「$i\to v_k\to j$」比当前 $A[i][j]$ 更短就改写：

$$
A^{(k)}[i][j]=\min\left(A^{(k-1)}[i][j],\ A^{(k-1)}[i][k]+A^{(k-1)}[k][j]\right)
$$

其中 $k=1,2,\dots,n$。

```
for (k = 0; k < n; k++)          // 依次允许经过 v_k
  for (i = 0; i < n; i++)
    for (j = 0; j < n; j++)
      if (A[i][k] + A[k][j] < A[i][j])
        A[i][j] = A[i][k] + A[k][j];   // 另设 path[i][j] 记录中转点以还原路径
```

**算例**（3 个顶点 $a,b,c$，初值为直达弧权）：

| $A$ | $a$ | $b$ | $c$ |
| --- | --- | --- | --- |
| $a$ | 0 | 4 | 11 |
| $b$ | 6 | 0 | 2 |
| $c$ | 3 | $\infty$ | 0 |

- 加入 $a$：$b\to c$ 经 $a$ 为 $6+11=17>2$，不变；$c\to b$ 经 $a$ 为 $3+4=7<\infty$，改为 7。
- 加入 $b$：$a\to c$ 经 $b$ 为 $4+2=6<11$，改为 6。
- 加入 $c$：$b\to a$ 经 $c$ 为 $2+3=5<6$，改为 5。

终值矩阵：

| $A$ | $a$ | $b$ | $c$ |
|:---:|:---:|:---:|:---:|
| $a$ | 0 | 4 | 6 |
| $b$ | 5 | 0 | 2 |
| $c$ | 3 | 7 | 0 |

复杂度 $O(n^3)$（三重循环）。对 $n$ 个顶点各跑一次 Dijkstra 也是 $O(n^3)$，但 Floyd 的代码更简单——这是它被单独采用的原因。

> **注意**：Floyd 按中转点逐个加入，不依赖「按路径长度递增定稿」，因此**允许负权边**（Dijkstra 不允许）；但图中**不能有负权回路**，否则最短路径无意义。课程只讨论非负权的情形。

> **★考点**：Floyd 求出的是**所有顶点对**的最短路径；只求一个源点到某个终点时仍用 Dijkstra，用 Floyd 反而多算。

<figure class="cpd-figure not-content" id="wz-w4-fig-14">
  <svg viewBox="0 0 700 248" role="img" aria-labelledby="wz-w4-fig-14-title">
    <title id="wz-w4-fig-14-title">Floyd 算法矩阵演进：逐个加入中转顶点更新最短路径</title>
    <defs>
      <marker id="wz-w4-arr-14" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <text class="fig-title" x="350" y="22" text-anchor="middle" font-size="12.5">Floyd 矩阵演进：A⁽ᵏ⁾[i][j] = min(A⁽ᵏ⁻¹⁾[i][j], A⁽ᵏ⁻¹⁾[i][k] + A⁽ᵏ⁻¹⁾[k][j])</text>
    <g stroke="var(--sl-color-accent)" stroke-width="1.4" fill="none" marker-end="url(#wz-w4-arr-14)">
      <path d="M 146 50 Q 190 36 234 50"/>
      <path d="M 234 62 Q 190 76 146 62"/>
      <line x1="238" y1="68" x2="202" y2="104"/>
      <line x1="138" y1="68" x2="178" y2="104"/>
      <path d="M 176 106 Q 146 92 134 70"/>
    </g>
    <g class="fig-box-blue">
      <circle cx="132" cy="56" r="13"/><circle cx="248" cy="56" r="13"/><circle cx="190" cy="112" r="13"/>
    </g>
    <g class="fig-blue" font-size="11.5" text-anchor="middle">
      <text x="132" y="60">a</text><text x="248" y="60">b</text><text x="190" y="116">c</text>
    </g>
    <g class="fig-muted" font-size="10" text-anchor="middle">
      <text x="190" y="38">4</text><text x="190" y="78">6</text>
      <text x="228" y="94">2</text><text x="172" y="88">11</text><text x="142" y="96">3</text>
    </g>
    <rect class="fig-box-subtle" x="300" y="42" width="374" height="72" rx="5"/>
    <g font-size="11">
      <text class="fig-label" x="314" y="62">三轮中转试探（每轮更新满足 i→k→j 更短的表项）：</text>
      <text class="fig-blue" x="314" y="82">• 加入 a：c→a→b = 3 + 4 = 7 &lt; ∞（更新 A[c][b]）</text>
      <text class="fig-accent" x="314" y="100" font-size="9.5">• 加入 b：a→b→c = 4 + 2 = 6 &lt; 11；加入 c：b→c→a = 2 + 3 = 5 &lt; 6</text>
    </g>
    <g class="fig-box">
      <rect x="28" y="142" width="120" height="84" rx="4"/>
      <rect x="198" y="142" width="120" height="84" rx="4"/>
      <rect x="368" y="142" width="120" height="84" rx="4"/>
      <rect x="538" y="142" width="120" height="84" rx="4"/>
    </g>
    <g class="fig-divider">
      <line x1="68" y1="142" x2="68" y2="226"/><line x1="108" y1="142" x2="108" y2="226"/>
      <line x1="28" y1="170" x2="148" y2="170"/><line x1="28" y1="198" x2="148" y2="198"/>
      <line x1="238" y1="142" x2="238" y2="226"/><line x1="278" y1="142" x2="278" y2="226"/>
      <line x1="198" y1="170" x2="318" y2="170"/><line x1="198" y1="198" x2="318" y2="198"/>
      <line x1="408" y1="142" x2="408" y2="226"/><line x1="448" y1="142" x2="448" y2="226"/>
      <line x1="368" y1="170" x2="488" y2="170"/><line x1="368" y1="198" x2="488" y2="198"/>
      <line x1="578" y1="142" x2="578" y2="226"/><line x1="618" y1="142" x2="618" y2="226"/>
      <line x1="538" y1="170" x2="658" y2="170"/><line x1="538" y1="198" x2="658" y2="198"/>
    </g>
    <g class="fig-line" marker-end="url(#wz-w4-arr-14)">
      <line x1="154" y1="184" x2="192" y2="184"/>
      <line x1="324" y1="184" x2="362" y2="184"/>
      <line x1="494" y1="184" x2="532" y2="184"/>
    </g>
    <g font-size="11" text-anchor="middle">
      <text class="fig-muted" x="88" y="135">A⁽⁻¹⁾（初始邻接矩阵）</text>
      <text class="fig-label" x="48" y="160">0</text><text class="fig-label" x="88" y="160">4</text><text class="fig-label" x="128" y="160">11</text>
      <text class="fig-label" x="48" y="188">6</text><text class="fig-label" x="88" y="188">0</text><text class="fig-label" x="128" y="188">2</text>
      <text class="fig-label" x="48" y="216">3</text><text class="fig-muted" x="88" y="216">∞</text><text class="fig-label" x="128" y="216">0</text>
      <text class="fig-blue" x="258" y="135">A⁽⁰⁾（加入 a）</text>
      <text class="fig-label" x="218" y="160">0</text><text class="fig-label" x="258" y="160">4</text><text class="fig-label" x="298" y="160">11</text>
      <text class="fig-label" x="218" y="188">6</text><text class="fig-label" x="258" y="188">0</text><text class="fig-label" x="298" y="188">2</text>
      <text class="fig-label" x="218" y="216">3</text><text class="fig-blue" x="258" y="216">7</text><text class="fig-label" x="298" y="216">0</text>
      <text class="fig-accent" x="428" y="135">A⁽¹⁾（加入 b）</text>
      <text class="fig-label" x="388" y="160">0</text><text class="fig-label" x="428" y="160">4</text><text class="fig-accent" x="468" y="160">6</text>
      <text class="fig-label" x="388" y="188">6</text><text class="fig-label" x="428" y="188">0</text><text class="fig-label" x="468" y="188">2</text>
      <text class="fig-label" x="388" y="216">3</text><text class="fig-label" x="428" y="216">7</text><text class="fig-label" x="468" y="216">0</text>
      <text class="fig-green" x="598" y="135">A⁽²⁾（加入 c，终值）</text>
      <text class="fig-label" x="558" y="160">0</text><text class="fig-label" x="598" y="160">4</text><text class="fig-label" x="638" y="160">6</text>
      <text class="fig-green" x="558" y="188">5</text><text class="fig-label" x="598" y="188">0</text><text class="fig-label" x="638" y="188">2</text>
      <text class="fig-label" x="558" y="216">3</text><text class="fig-label" x="598" y="216">7</text><text class="fig-label" x="638" y="216">0</text>
    </g>
  </svg>
  <figcaption>Floyd 算法矩阵演进：依次以 a、b、c 为中间点试探松弛，高亮数值为当轮被改写的最短路径长度</figcaption>
</figure>

> **交互演示**：[Dijkstra 单源与 Floyd 全源最短路径](/lab/chapter-7/#lab-dijkstra)

### AOV 网与拓扑排序

**有向无环图**（DAG）：有向且不含回路。它比有向树宽松——顶点可以有多个前驱、多个后继，但不是树。

用 DAG 描述一个工程：工程分成若干**活动**（子工程）。两种表示法：

| 网 | 顶点表示 | 弧表示 | 用途 |
| --- | --- | --- | --- |
| **AOV 网** | 活动 | 活动间的先后制约关系 | 拓扑排序（排课、排工序） |
| **AOE 网** | 事件（活动开始/结束） | 活动，权为持续时间 | 关键路径（工期估算） |

AOV 网中的术语：若从 $i$ 到 $j$ 有路径，则 $i$ 是 $j$ 的**前驱**、$j$ 是 $i$ 的**后继**；若有直接边 $\langle i,j\rangle$，则 $i$ 是 $j$ 的**直接前驱**、$j$ 是 $i$ 的**直接后继**。

> **注意**：AOV 网**不允许回路**。有回路意味着某项活动以自己为先决条件（$c_1$ 要先修 $c_2$、$c_2$ 要先修 $c_3$、$c_3$ 又要先修 $c_1$），谁都无法先开始，工程无法启动。

**拓扑排序**：把 AOV 网的全部顶点排成一个**线性序列**，使得对任意弧 $\langle i,j\rangle$，序列中 $i$ 必在 $j$ 之前；这样的序列称**拓扑有序序列**，求得它的过程就是拓扑排序。同一 AOV 网的拓扑序列**不唯一**（同时存在多个入度为 0 的顶点时，次序可交换）。

### 拓扑排序的步骤与判环

步骤（课程用的「删点删弧」法）：

1. 在 DAG 中选一个**入度为 0**（无前驱）的顶点输出。
2. 从图中删除该顶点，以及所有以它为**弧尾**的弧（它已执行完，不再制约别人）。
3. 重复 1、2，直到全部顶点输出（或图中再无入度为 0 的顶点）。

以课程表为例（$c_1$ 程序设计、$c_2$ 离散数学先修 $c_3$ 数据结构，$c_9$ 高等数学先修线性代数/普通物理等）：先输出 $c_1$（或 $c_9$），删去其出弧后 $c_2$ 无前驱，再输出 $c_2$……如此得到 $c_{11},\dots,c_8$ 一类序列，且任一条边 $\langle c_3,c_8\rangle$ 都满足 $c_3$ 排在 $c_8$ 之前。

**判环**：对图做拓扑排序，若**全部 $n$ 个顶点都能输出**，则无环；若中途找不到入度为 0 的顶点、**剩余顶点无法输出**，则必有环——剩下的顶点互相等待，谁也删不掉。

实现要点：入度表 + 栈/队列存放入度为 0 的顶点，删除顶点时把它所有后继的入度减 1。

> **补充**：课程未展开实现；用邻接表实现的时间复杂度为 $O(n+e)$（每个顶点、每条边各处理一次）。

<figure class="cpd-figure not-content" id="wz-w4-fig-15">
  <svg viewBox="0 0 700 248" role="img" aria-labelledby="wz-w4-fig-15-title">
    <title id="wz-w4-fig-15-title">AOV 网拓扑排序删点删弧逐步追踪</title>
    <defs>
      <marker id="wz-w4-arr-15" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <text class="fig-title" x="350" y="22" text-anchor="middle" font-size="12.5">拓扑排序（删点删弧法）：选入度 0 顶点输出 → 删其出弧 → 后继入度减 1</text>
    <g stroke="var(--sl-color-gray-4)" stroke-width="1.3" fill="none" marker-end="url(#wz-w4-arr-15)">
      <line x1="56" y1="88" x2="86" y2="68"/>
      <line x1="56" y1="102" x2="86" y2="122"/>
      <line x1="112" y1="66" x2="140" y2="88"/>
      <line x1="112" y1="124" x2="140" y2="102"/>
      <line x1="114" y1="132" x2="146" y2="146"/>
      <line x1="164" y1="106" x2="164" y2="132"/>
      <line x1="286" y1="66" x2="314" y2="88"/>
      <line x1="286" y1="124" x2="314" y2="102"/>
      <line x1="288" y1="132" x2="320" y2="146"/>
      <line x1="338" y1="106" x2="338" y2="132"/>
      <line x1="512" y1="106" x2="512" y2="132"/>
    </g>
    <g class="fig-line-dashed">
      <line x1="230" y1="88" x2="260" y2="68"/>
      <line x1="230" y1="102" x2="260" y2="122"/>
      <line x1="460" y1="66" x2="488" y2="88"/>
      <line x1="460" y1="124" x2="488" y2="102"/>
      <line x1="462" y1="132" x2="494" y2="146"/>
    </g>
    <g class="fig-line" marker-end="url(#wz-w4-arr-15)">
      <line x1="184" y1="96" x2="204" y2="96"/>
      <line x1="358" y1="96" x2="378" y2="96"/>
      <line x1="532" y1="96" x2="552" y2="96"/>
    </g>
    <g class="fig-box-accent">
      <circle cx="44" cy="96" r="12"/>
      <circle cx="272" cy="60" r="12"/><circle cx="272" cy="130" r="12"/>
      <circle cx="512" cy="96" r="12"/>
    </g>
    <g class="fig-box">
      <circle cx="98" cy="60" r="12"/><circle cx="98" cy="130" r="12"/><circle cx="164" cy="96" r="12"/><circle cx="164" cy="148" r="12"/>
      <circle cx="338" cy="96" r="12"/><circle cx="338" cy="148" r="12"/>
      <circle cx="512" cy="148" r="12"/>
    </g>
    <g class="fig-box-dashed">
      <circle cx="218" cy="96" r="12"/>
      <circle cx="446" cy="60" r="12"/><circle cx="446" cy="130" r="12"/>
    </g>
    <g font-size="10.5" text-anchor="middle">
      <text class="fig-accent" x="44" y="100">v₁</text><text class="fig-label" x="98" y="64">v₂</text><text class="fig-label" x="98" y="134">v₃</text><text class="fig-label" x="164" y="100">v₄</text><text class="fig-label" x="164" y="152">v₅</text>
      <text class="fig-muted" x="218" y="100">v₁</text><text class="fig-accent" x="272" y="64">v₂</text><text class="fig-accent" x="272" y="134">v₃</text><text class="fig-label" x="338" y="100">v₄</text><text class="fig-label" x="338" y="152">v₅</text>
      <text class="fig-muted" x="446" y="64">v₂</text><text class="fig-muted" x="446" y="134">v₃</text><text class="fig-accent" x="512" y="100">v₄</text><text class="fig-label" x="512" y="152">v₅</text>
    </g>
    <rect class="fig-box-green" x="562" y="56" width="116" height="96" rx="5"/>
    <g font-size="11" text-anchor="middle">
      <text class="fig-green" x="620" y="78">④ 删 v₄, v₅</text>
      <text class="fig-label" x="620" y="100">拓扑序列完成：</text>
      <text class="fig-green" x="620" y="120">v₁, v₂, v₃, v₄, v₅</text>
      <text class="fig-muted" x="620" y="140">共 5 点，无环 ✓</text>
    </g>
    <g class="fig-muted" font-size="10.5" text-anchor="middle">
      <text x="104" y="182">① 初始入度 0：[v₁]</text>
      <text x="278" y="182">② 删 v₁ → [v₂, v₃] 入度 0</text>
      <text x="462" y="182">③ 删 v₂, v₃ → [v₄] 入度 0</text>
    </g>
    <rect class="fig-box-subtle" x="24" y="198" width="654" height="36" rx="5"/>
    <text class="fig-muted" x="350" y="220" text-anchor="middle" font-size="11">判环准则：若输出顶点数 = n 则无环；若栈空时仍有未输出顶点（入度均 &gt; 0），则图中必存在有向环</text>
  </svg>
  <figcaption>AOV 网拓扑排序“删点删弧”逐步追踪：橙框标出当前入度为 0 的候选顶点，虚线标出已删除的顶点与弧</figcaption>
</figure>

### AOE 网与关键路径的四个量

**AOE 网**：弧表示活动、弧上的权表示活动持续时间；顶点表示**事件**——既表示其前驱活动已结束，也表示其后继活动可以开始。

- **源点**：入度为 0 的顶点，代表整个工程开始的时刻；
- **汇点**：出度为 0 的顶点，代表整个工程结束。

**关键路径**：从源点到汇点**路径长度最长**的路径（长度 = 路径上各活动持续时间之和）。其长度就是工程的最短工期；关键路径可能不止一条。关键路径上的活动即**关键活动**——只有压缩关键活动才可能缩短总工期。

四个描述量：

| 量 | 含义 |
| --- | --- |
| $ve(j)$ | 事件（顶点）$j$ 的**最早**发生时间 |
| $vl(j)$ | 事件（顶点）$j$ 的**最迟**发生时间 |
| $e(i)$ | 活动（弧）$i$ 的**最早**开始时间 |
| $l(i)$ | 活动（弧）$i$ 的**最迟**开始时间 |

计算规则：

- $ve$ 正向递推：$ve(v_s)=0$；$ve(j)=\max\{ve(i)+w(i,j)\}$，对所有以 $j$ 为弧头的弧取最大（要等最慢的前驱活动结束）。
- $vl$ 反向递推：$vl(v_t)=ve(v_t)$；$vl(i)=\min\{vl(j)-w(i,j)\}$，对所有以 $i$ 为弧尾的弧取最小（不能拖累任何后继）。
- 设活动 $i$ 对应弧 $\langle j,k\rangle$：$e(i)=ve(j)$，$l(i)=vl(k)-w(j,k)$。
- **时间余量** $d(i)=l(i)-e(i)$；余量为 0 的活动即**关键活动**，由关键活动连成的源点到汇点路径即**关键路径**。

求关键路径的顺序：先算 $ve$（正推取 max），再算 $vl$（逆推取 min），再算每个活动的 $e,l$，最后取 $l-e=0$ 者。

### 关键路径算例

工程含 11 项活动，AOE 网如下（源点 $v_1$，汇点 $v_9$，蓝线为关键活动）：

<figure class="cpd-figure not-content" id="wz-w4-fig-8">
  <svg viewBox="0 0 680 282" role="img" aria-labelledby="wz-fig-23">
    <title id="wz-fig-23">AOE 网与关键路径算例</title>
    <defs>
      <marker id="wz-arr-23" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M1.5,1.5 L8.5,5 L1.5,8.5" fill="none" stroke="context-stroke" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
      </marker>
    </defs>
    <g stroke="var(--sl-color-gray-4)" stroke-width="1.3" marker-end="url(#wz-arr-23)" fill="none">
      <line x1="76" y1="140" x2="152" y2="140"/>
      <line x1="72" y1="152" x2="156" y2="218"/>
      <line x1="188" y1="136" x2="294" y2="106"/>
      <line x1="188" y1="226" x2="294" y2="226"/>
      <line x1="330" y1="218" x2="438" y2="152"/>
    </g>
    <g stroke="var(--sl-color-accent)" stroke-width="2.2" marker-end="url(#wz-arr-23)" fill="none">
      <line x1="72" y1="128" x2="156" y2="68"/>
      <line x1="188" y1="64" x2="294" y2="96"/>
      <line x1="330" y1="94" x2="436" y2="66"/>
      <line x1="330" y1="108" x2="436" y2="136"/>
      <line x1="472" y1="64" x2="588" y2="94"/>
      <line x1="472" y1="138" x2="588" y2="108"/>
    </g>
    <g class="fig-box">
      <circle cx="170" cy="140" r="17"/>
      <circle cx="170" cy="226" r="17"/>
      <circle cx="312" cy="226" r="17"/>
    </g>
    <g class="fig-box-accent">
      <circle cx="58" cy="140" r="17"/>
      <circle cx="170" cy="58" r="17"/>
      <circle cx="312" cy="100" r="17"/>
      <circle cx="454" cy="58" r="17"/>
      <circle cx="454" cy="142" r="17"/>
      <circle cx="606" cy="100" r="17"/>
    </g>
    <g font-size="12" text-anchor="middle">
      <text class="fig-accent" x="58" y="145">v₁</text>
      <text class="fig-accent" x="170" y="63">v₂</text>
      <text class="fig-label" x="170" y="145">v₃</text>
      <text class="fig-label" x="170" y="231">v₄</text>
      <text class="fig-accent" x="312" y="105">v₅</text>
      <text class="fig-label" x="312" y="231">v₆</text>
      <text class="fig-accent" x="454" y="63">v₇</text>
      <text class="fig-accent" x="454" y="147">v₈</text>
      <text class="fig-accent" x="606" y="105">v₉</text>
    </g>
    <g class="fig-muted" font-size="11" text-anchor="middle">
      <text x="114" y="130">a₂, 4</text>
      <text x="104" y="198">a₃, 5</text>
      <text x="242" y="132">a₅, 1</text>
      <text x="241" y="218">a₆, 2</text>
      <text x="386" y="198">a₉, 4</text>
      <text x="58" y="176">源点</text>
      <text x="606" y="136">汇点</text>
    </g>
    <g class="fig-accent" font-size="11" text-anchor="middle">
      <text x="106" y="88">a₁, 6</text>
      <text x="242" y="70">a₄, 1</text>
      <text x="382" y="68">a₇, 9</text>
      <text x="394" y="114">a₈, 7</text>
      <text x="530" y="68">a₁₀, 2</text>
      <text x="530" y="138">a₁₁, 4</text>
    </g>
    <text class="fig-muted" x="340" y="266" text-anchor="middle" font-size="11.5">实亮蓝线为两条并行的关键路径（总工期 18）：v₁→v₂→v₅→v₇→v₉ 与 v₁→v₂→v₅→v₈→v₉</text>
  </svg>
  <figcaption>AOE 网与关键路径：所有 l − e = 0 的关键活动连成源点到汇点的最长路径</figcaption>
</figure>

**第一步：求各顶点的 $ve$（正推取 max）**

$ve(v_1)=0$；$ve(v_2)=0+6=6$；$ve(v_3)=0+4=4$；$ve(v_4)=0+5=5$；

$ve(v_5)=\max\{6+1,\ 4+1\}=7$；$ve(v_6)=5+2=7$；$ve(v_7)=7+9=16$；

$ve(v_8)=\max\{7+7,\ 7+4\}=14$；$ve(v_9)=\max\{16+2,\ 14+4\}=18$。

**第二步：求各顶点的 $vl$（逆推取 min，$vl(v_9)=ve(v_9)=18$）**

| 顶点 | $v_1$ | $v_2$ | $v_3$ | $v_4$ | $v_5$ | $v_6$ | $v_7$ | $v_8$ | $v_9$ |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| $ve$ | 0 | 6 | 4 | 5 | 7 | 7 | 16 | 14 | 18 |
| $vl$ | 0 | 6 | 6 | 8 | 7 | 10 | 16 | 14 | 18 |

其中 $vl(v_8)=18-4=14$，$vl(v_7)=18-2=16$，$vl(v_6)=14-4=10$，$vl(v_5)=\min\{16-9,\ 14-7\}=7$，$vl(v_4)=10-2=8$，$vl(v_3)=7-1=6$，$vl(v_2)=7-1=6$，$vl(v_1)=\min\{6-6,\ 6-4,\ 8-5\}=0$。

**第三步：求各活动的 $e,l$ 与时间余量**

| 活动 | 弧 | 权 $w$ | $e=ve(j)$ | $l=vl(k)-w$ | $l-e$ | 关键活动 |
| --- | --- | --- | --- | --- | --- | --- |
| $a_1$ | $\langle v_1,v_2\rangle$ | 6 | 0 | $6-6=0$ | 0 | ✓ |
| $a_2$ | $\langle v_1,v_3\rangle$ | 4 | 0 | $6-4=2$ | 2 | |
| $a_3$ | $\langle v_1,v_4\rangle$ | 5 | 0 | $8-5=3$ | 3 | |
| $a_4$ | $\langle v_2,v_5\rangle$ | 1 | 6 | $7-1=6$ | 0 | ✓ |
| $a_5$ | $\langle v_3,v_5\rangle$ | 1 | 4 | $7-1=6$ | 2 | |
| $a_6$ | $\langle v_4,v_6\rangle$ | 2 | 5 | $10-2=8$ | 3 | |
| $a_7$ | $\langle v_5,v_7\rangle$ | 9 | 7 | $16-9=7$ | 0 | ✓ |
| $a_8$ | $\langle v_5,v_8\rangle$ | 7 | 7 | $14-7=7$ | 0 | ✓ |
| $a_9$ | $\langle v_6,v_8\rangle$ | 4 | 7 | $14-4=10$ | 3 | |
| $a_{10}$ | $\langle v_7,v_9\rangle$ | 2 | 16 | $18-2=16$ | 0 | ✓ |
| $a_{11}$ | $\langle v_8,v_9\rangle$ | 4 | 14 | $18-4=14$ | 0 | ✓ |

**结论**：关键活动为 $a_1,a_4,a_7,a_8,a_{10},a_{11}$，构成**两条**关键路径 $v_1\to v_2\to v_5\to v_7\to v_9$ 与 $v_1\to v_2\to v_5\to v_8\to v_9$，长度均为 18，故工程最短工期为 18 个时间单位。

> **★考点**：求关键路径的完整流程 = $ve$ 正推取 max → $vl$ 逆推取 min → 逐活动算 $e,l$ → $l-e=0$ 者为关键活动。

> **注意**：若有多条关键路径，必须**同时**压缩各自的关键活动才能缩短工期，只加快其中一条无效。压缩关键活动也不是越多越好——压到一定程度，关键路径会转移到别的路径上，必须重新计算。

<figure class="cpd-figure not-content" id="wz-w4-fig-16">
  <svg viewBox="0 0 700 252" role="img" aria-labelledby="wz-w4-fig-16-title">
    <title id="wz-w4-fig-16-title">AOE 网 ve 正推取 max 与 vl 逆推取 min 及时间余量示意</title>
    <defs>
      <marker id="wz-w4-arr-16" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <text class="fig-title" x="175" y="22" text-anchor="middle" font-size="12.5">正推 ve(j)：汇合点取 max（等最慢前驱）</text>
    <text class="fig-title" x="525" y="22" text-anchor="middle" font-size="12.5">逆推 vl(i)：分支点取 min（不拖累后继）</text>
    <line class="fig-divider" x1="350" y1="16" x2="350" y2="156"/>
    <g stroke="var(--sl-color-accent)" stroke-width="1.8" fill="none" marker-end="url(#wz-w4-arr-16)">
      <line x1="94" y1="60" x2="212" y2="86"/>
    </g>
    <g stroke="var(--sl-color-gray-4)" stroke-width="1.4" fill="none" marker-end="url(#wz-w4-arr-16)">
      <line x1="94" y1="124" x2="212" y2="98"/>
    </g>
    <g class="fig-box-accent">
      <circle cx="76" cy="56" r="15"/><circle cx="230" cy="92" r="16"/>
    </g>
    <circle class="fig-box" cx="76" cy="128" r="15"/>
    <g font-size="11" text-anchor="middle">
      <text class="fig-accent" x="76" y="60">v₂</text><text class="fig-muted" x="76" y="84">ve=6</text>
      <text class="fig-label" x="76" y="132">v₃</text><text class="fig-muted" x="76" y="156">ve=4</text>
      <text class="fig-accent" x="230" y="96">v₅</text>
      <text class="fig-accent" x="152" y="62">a₄: 1 → 6+1=7</text>
      <text class="fig-muted" x="152" y="124">a₅: 1 → 4+1=5</text>
      <text class="fig-accent" x="278" y="96">ve=max&#123;7,5&#125;=7</text>
    </g>
    <g stroke="var(--sl-color-blue)" stroke-width="1.8" fill="none" marker-end="url(#wz-w4-arr-16)">
      <line x1="454" y1="86" x2="572" y2="60"/>
      <line x1="454" y1="98" x2="572" y2="124"/>
    </g>
    <g class="fig-box-blue">
      <circle cx="436" cy="92" r="16"/><circle cx="590" cy="56" r="15"/><circle cx="590" cy="128" r="15"/>
    </g>
    <g font-size="11" text-anchor="middle">
      <text class="fig-blue" x="436" y="96">v₅</text>
      <text class="fig-blue" x="590" y="60">v₇</text><text class="fig-muted" x="590" y="84">vl=16</text>
      <text class="fig-blue" x="590" y="132">v₈</text><text class="fig-muted" x="590" y="156">vl=14</text>
      <text class="fig-blue" x="512" y="62">a₇: 9 → 16−9=7</text>
      <text class="fig-blue" x="512" y="124">a₈: 7 → 14−7=7</text>
      <text class="fig-blue" x="390" y="96">vl=min&#123;7,7&#125;=7</text>
    </g>
    <rect class="fig-box-subtle" x="24" y="170" width="652" height="68" rx="5"/>
    <g font-size="11">
      <text class="fig-label" x="38" y="190">活动时间余量 d(i) = l(i) − e(i) 对比（以汇入 v₅ 的 a₄ 与 a₅ 为例）：</text>
      <text class="fig-accent" x="38" y="210">• 关键活动 a₄ ⟨v₂, v₅⟩：e = ve(v₂) = 6，l = vl(v₅) − 1 = 6，余量 d = 0（不可延迟）</text>
      <text class="fig-muted" x="38" y="228">• 非关键活动 a₅ ⟨v₃, v₅⟩：e = ve(v₃) = 4，l = vl(v₅) − 1 = 6，余量 d = 2（可推迟 2 单位而不影响总工期）</text>
    </g>
  </svg>
  <figcaption>AOE 网双遍递推与余量判别：正推 ve 取 max 保证前驱全完成，逆推 vl 取 min 保证后继不延误，l − e = 0 即关键活动</figcaption>
</figure>

> **交互演示**：[拓扑排序与 AOE 网关键路径](/lab/chapter-7/#lab-topological)

## 第7章 查找

### 查找表与查找的基本概念

**查找表**是由同一类型的数据元素（记录）构成的集合，元素之间关系松散，**没有严格的前驱、后继约束**，因此可按需要组织成线性表、树表或散列表——怎么组织取决于查找操作怎么做才方便、才快。

- **记录**：由若干**数据项**组成；数据项是不可再分的最小数据单位。
- **关键字**：某个数据项的值，能标识一个数据元素（记录）。
  - **主关键字**：可**唯一**标识一条记录，如准考证号。
  - **次关键字**：可能标识多条记录，如姓名、某门课成绩。
- **查找**：根据给定值，在查找表中确定关键字值等于给定值的那条记录。
- 查找**成功**：返回该记录的信息或其位置；查找**失败**：返回空记录、空指针，或约定的 `0`、`-1`。
- 查找的四种目的：① 判断是否存在；② 取出该记录的其它属性；③ 不存在则**插入**；④ 存在则**删除**。

| 类型 | 操作 | 典型结构 |
|---|---|---|
| **静态查找表** | 只做查询/检索，查完表不变 | 顺序表（顺序、折半、分块查找） |
| **动态查找表** | 查找过程中插入、删除，表会变化 | 二叉排序树、平衡二叉树、红黑树、B 树、B+ 树 |

> **注意**：关键字是“数据项的值”，不是整条记录；主/次的区别只在于能否唯一确定一条记录。

### 平均查找长度 ASL

查找算法不用通用时间复杂度作主指标，而用**平均查找长度**（Average Search Length）：查找过程中关键字的**平均比较次数**。

$$
ASL=\sum_{i=1}^{n}P_iC_i,\qquad \sum_{i=1}^{n}P_i=1
$$

其中 $n$ 为记录数，$P_i$ 为查找第 $i$ 条记录的概率，$C_i$ 为找到它所需的比较次数。等概率 $P_i=1/n$ 时：

$$
ASL=\frac{1}{n}\sum_{i=1}^{n}C_i
$$

- 成功与失败要分开算：$ASL_{\text{succ}}$、$ASL_{\text{fail}}$ 的计算口径不同（失败时通常比较到空位置/哨兵）。
- 比较算法优劣时最终仍看数量级：$O(1)$、$O(\log n)$、$O(n)$。

### 顺序查找

顺序查找（线性查找）用于**静态查找表**，用顺序表或线性链表存储均可，**表中元素可以无序**（有序也能用，只是浪费了有序性）。

```c
typedef struct { KeyType key; /* 其它数据项 */ } ElemType;
typedef struct { ElemType *R; int length; } SSTable;
// R[1..length] 存放元素，R[0] 留作哨兵
```

从后往前的朴素写法（算法 7.1）：

```c
int Search_Seq(SSTable ST, KeyType key) {
  for (int i = ST.length; i >= 1; --i)
    if (ST.R[i].key == key) return i;
  return 0;                       // 0 表示查找失败
}
```

**哨兵（监视哨）改进**（算法 7.2）：把待查关键字存入 `R[0]`，循环内**不必再判断下标越界**，每轮只比较一次：

```c
int Search_Seq(SSTable ST, KeyType key) {
  ST.R[0].key = key;                       // 哨兵
  int i;
  for (i = ST.length; ST.R[i].key != key; --i) ;   // 注意：分号，循环体为空
  return i;                                // 返回 0 即失败（在哨兵处"找到"）
}
```

> **注意**：循环体为空语句时，`for(...)` 后的分号不能丢，否则后一条语句会变成循环体。

性能分析（元素在下标 $1..n$）：

- 查找第 $i$ 个元素：需比较 $n-i+1$ 次；失败需比较 $n+1$ 次（最后与哨兵相等）。
- $ASL_{\text{succ}}=\frac{1}{n}\sum_{i=1}^{n}(n-i+1)=\frac{n+1}{2}$，$ASL_{\text{fail}}=n+1$。
- 时间复杂度 $O(n)$，空间复杂度 $O(1)$（仅一个哨兵单元）。带哨兵后每轮省一次比较，元素多时平均时间约减半。


<figure class="cpd-figure not-content" id="wz-w5-fig-1">
  <svg viewBox="0 0 700 248" role="img" aria-labelledby="wz-w5-title-1">
    <title id="wz-w5-title-1">顺序查找监视哨 R[0] 机制与非等概率优化</title>
    <defs>
      <marker id="wz-w5-arr-1" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="14" width="668" height="128" rx="8"/>
    <text class="fig-title" x="30" y="34" font-size="12.5">① 监视哨 R[0]：从后往前扫描（i = n → 1 → 0），省去每轮越界判断 i ≥ 1</text>
    <rect class="fig-box-accent" x="34" y="54" width="68" height="34" rx="4"/>
    <rect class="fig-box" x="116" y="54" width="68" height="34" rx="4"/>
    <rect class="fig-box" x="184" y="54" width="68" height="34" rx="4"/>
    <rect class="fig-box-green" x="252" y="54" width="68" height="34" rx="4"/>
    <rect class="fig-box" x="320" y="54" width="68" height="34" rx="4"/>
    <rect class="fig-box" x="388" y="54" width="68" height="34" rx="4"/>
    <rect class="fig-box" x="456" y="54" width="68" height="34" rx="4"/>
    <rect class="fig-box-blue" x="524" y="54" width="68" height="34" rx="4"/>
    <g font-size="12.5" text-anchor="middle">
      <text class="fig-accent" x="68" y="76">25</text>
      <text class="fig-label" x="150" y="76">13</text>
      <text class="fig-label" x="218" y="76">48</text>
      <text class="fig-green" x="286" y="76">25</text>
      <text class="fig-label" x="354" y="76">76</text>
      <text class="fig-label" x="422" y="76">38</text>
      <text class="fig-label" x="490" y="76">65</text>
      <text class="fig-blue" x="558" y="76">97</text>
    </g>
    <g class="fig-muted" font-size="10.5" text-anchor="middle">
      <text class="fig-accent" x="68" y="104">0（哨兵）</text>
      <text x="150" y="104">1</text>
      <text x="218" y="104">2</text>
      <text class="fig-green" x="286" y="104">3（命中）</text>
      <text x="354" y="104">4</text>
      <text x="422" y="104">5</text>
      <text x="490" y="104">6</text>
      <text class="fig-blue" x="558" y="104">7（起点）</text>
    </g>
    <path d="M 558 46 Q 422 28 292 48" fill="none" stroke="var(--sl-color-green)" stroke-width="1.5" marker-end="url(#wz-w5-arr-1)"/>
    <text class="fig-green" x="430" y="42" text-anchor="middle" font-size="10.5">查 25：比 5 次命中，返回 i = 3</text>
    <path d="M 558 112 Q 310 132 74 110" fill="none" stroke="var(--sl-color-orange)" stroke-width="1.4" stroke-dasharray="4 3" marker-end="url(#wz-w5-arr-1)"/>
    <text class="fig-orange" x="316" y="132" text-anchor="middle" font-size="10.5">若查 88（失败）：哨兵置 88，比 n + 1 = 8 次在 i = 0 处停下，返回 0</text>
    <text class="fig-muted" x="640" y="68" text-anchor="middle" font-size="11">ASL_succ = (n+1)/2</text>
    <text class="fig-muted" x="640" y="86" text-anchor="middle" font-size="11">ASL_fail = n + 1</text>
    <rect class="fig-box-subtle" x="16" y="152" width="668" height="82" rx="8"/>
    <text class="fig-title" x="30" y="172" font-size="12.5">② 非等概率优化：将访问概率 Pᵢ 高的元素放在表尾，使从后往前扫描的比较次数 Cᵢ 更小</text>
    <rect class="fig-box" x="140" y="186" width="90" height="32" rx="4"/>
    <rect class="fig-box" x="234" y="186" width="90" height="32" rx="4"/>
    <rect class="fig-box-blue" x="328" y="186" width="90" height="32" rx="4"/>
    <rect class="fig-box-green" x="422" y="186" width="90" height="32" rx="4"/>
    <g font-size="11.5" text-anchor="middle">
      <text class="fig-muted" x="185" y="206">低频 P = 0.05</text>
      <text class="fig-muted" x="279" y="206">低频 P = 0.15</text>
      <text class="fig-blue" x="373" y="206">高频 P = 0.30</text>
      <text class="fig-green" x="467" y="206">最高 P = 0.50</text>
    </g>
    <line class="fig-line-accent" x1="590" y1="202" x2="520" y2="202" marker-end="url(#wz-w5-arr-1)"/>
    <text class="fig-accent" x="634" y="206" text-anchor="middle" font-size="11">从表尾先查</text>
    <text class="fig-muted" x="78" y="206" text-anchor="middle" font-size="11">R[0] 哨兵</text>
  </svg>
  <figcaption>顺序查找哨兵 R[0] 机制与非等概率存储优化：高频记录放靠后可显著降低 ASL</figcaption>
</figure>
非等概率时提高效率的办法：按查找概率安排存储——**概率高**的元素放**靠后**（从后往前查，靠后比较次数少），概率低的放前面，从而降低总的平均比较次数；或给记录增设“访问频度”域，按频度动态排序；或查到后把元素**移到表头**。

| 优点 | 缺点 |
|---|---|
| 算法简单；对逻辑次序无要求；顺序表、链表都能用，适应面最广 | $ASL$ 大、$O(n)$，$n$ 大时太慢 |

### 折半查找与判定树

折半查找（二分/对分查找）要求：表中记录**按关键字有序**（递增或非递减），且**只能顺序存储**（需随机访问下标，链表无法求中点）。

思想：每比较一次，把待查区间缩小一半。设 `low`、`high` 为区间下界、上界，`mid` 为中点：

```c
int Search_Bin(SSTable ST, KeyType key) {
  int low = 1, high = ST.length, mid;
  while (low <= high) {
    mid = (low + high) / 2;                 // 向下取整
    if (ST.R[mid].key == key) return mid;   // 找到
    else if (key < ST.R[mid].key) high = mid - 1;
    else low = mid + 1;
  }
  return 0;                                 // low > high：区间为空，失败
}
```

递归形式只在参数上变化：`low > high` 返回 0；否则算 `mid`，相等返回 `mid`，小于则递归左半区，大于则递归右半区。**结束条件只有两个：找到，或 `low > high`。**

**判定树**：以当前区间的中点记录为根，左半区间递归为左子树、右半区间递归为右子树。圆形结点是查找**成功**的结点，为它们补上的方形（外部）结点代表**失败**区间，共 $n+1$ 个。

- 查找任一元素的比较次数 = 该结点**所在层数**（即根到它的路径上结点数）。
- 树高 $h=\lfloor \log_2 n\rfloor+1$，即**最大比较次数**；成功、失败比较次数都不超过 $h$。
- 判定树是平衡二叉树（任一结点左右子树高度差不超过 1），前 $h-1$ 层是满的，只有最底层可能不满。
- 满树时 $ASL_{\text{succ}}=\frac{n+1}{n}\log_2(n+1)-1\approx \log_2(n+1)-1$，数量级 $O(\log n)$。

$n=11$ 的例子：根为下标 6；第 2 层为 3、9；第 3 层为 1、4、7、10；第 4 层为 2、5、8、11。

$$
ASL=\frac{1\times1+2\times2+4\times3+4\times4}{11}=\frac{33}{11}=3
$$

对比同样 11 个元素的顺序查找 $ASL=(11+1)/2=6$，折半明显更快，且 $n$ 越大差距越大（对数级 vs 线性级）。

<figure class="cpd-figure not-content" id="wz-w5-fig-2">
  <svg viewBox="0 0 700 356" role="img" aria-labelledby="wz-w5-title-2">
    <title id="wz-w5-title-2">n = 11 有序表的折半查找判定树（含 11 个成功圆形结点与 12 个失败方形结点）</title>
    <g class="fig-line">
      <line x1="406" y1="36" x2="262" y2="90"/><line x1="406" y1="36" x2="550" y2="90"/>
      <line x1="262" y1="90" x2="190" y2="148"/><line x1="262" y1="90" x2="334" y2="148"/>
      <line x1="550" y1="90" x2="478" y2="148"/><line x1="550" y1="90" x2="622" y2="148"/>
      <line x1="190" y1="148" x2="158" y2="208"/><line x1="190" y1="148" x2="222" y2="208"/>
      <line x1="334" y1="148" x2="302" y2="208"/><line x1="334" y1="148" x2="366" y2="208"/>
      <line x1="478" y1="148" x2="446" y2="208"/><line x1="478" y1="148" x2="510" y2="208"/>
      <line x1="622" y1="148" x2="590" y2="208"/><line x1="622" y1="148" x2="654" y2="208"/>
      <line x1="222" y1="208" x2="202" y2="264"/><line x1="222" y1="208" x2="242" y2="264"/>
      <line x1="366" y1="208" x2="346" y2="264"/><line x1="366" y1="208" x2="386" y2="264"/>
      <line x1="510" y1="208" x2="490" y2="264"/><line x1="510" y1="208" x2="530" y2="264"/>
      <line x1="654" y1="208" x2="634" y2="264"/><line x1="654" y1="208" x2="674" y2="264"/>
    </g>
    <circle class="fig-box-accent" cx="406" cy="36" r="15"/>
    <g class="fig-box-blue">
      <circle cx="262" cy="90" r="15"/><circle cx="550" cy="90" r="15"/>
      <circle cx="190" cy="148" r="14"/><circle cx="334" cy="148" r="14"/>
      <circle cx="478" cy="148" r="14"/><circle cx="622" cy="148" r="14"/>
      <circle cx="222" cy="208" r="14"/><circle cx="366" cy="208" r="14"/>
      <circle cx="510" cy="208" r="14"/><circle cx="654" cy="208" r="14"/>
    </g>
    <g class="fig-box-orange">
      <rect x="148" y="198" width="20" height="20" rx="3"/><rect x="292" y="198" width="20" height="20" rx="3"/>
      <rect x="436" y="198" width="20" height="20" rx="3"/><rect x="580" y="198" width="20" height="20" rx="3"/>
      <rect x="193" y="255" width="18" height="18" rx="3"/><rect x="233" y="255" width="18" height="18" rx="3"/>
      <rect x="337" y="255" width="18" height="18" rx="3"/><rect x="377" y="255" width="18" height="18" rx="3"/>
      <rect x="481" y="255" width="18" height="18" rx="3"/><rect x="521" y="255" width="18" height="18" rx="3"/>
      <rect x="625" y="255" width="18" height="18" rx="3"/><rect x="665" y="255" width="18" height="18" rx="3"/>
    </g>
    <g font-size="12" text-anchor="middle">
      <text class="fig-accent" x="406" y="40">6</text>
      <text class="fig-blue" x="262" y="94">3</text><text class="fig-blue" x="550" y="94">9</text>
      <text class="fig-blue" x="190" y="152">1</text><text class="fig-blue" x="334" y="152">4</text>
      <text class="fig-blue" x="478" y="152">7</text><text class="fig-blue" x="622" y="152">10</text>
      <text class="fig-blue" x="222" y="212">2</text><text class="fig-blue" x="366" y="212">5</text>
      <text class="fig-blue" x="510" y="212">8</text><text class="fig-blue" x="654" y="212">11</text>
    </g>
    <g class="fig-orange" font-size="9.5" text-anchor="middle">
      <text x="158" y="211">×</text><text x="302" y="211">×</text>
      <text x="446" y="211">×</text><text x="590" y="211">×</text>
      <text x="202" y="267">×</text><text x="242" y="267">×</text>
      <text x="346" y="267">×</text><text x="386" y="267">×</text>
      <text x="490" y="267">×</text><text x="530" y="267">×</text>
      <text x="634" y="267">×</text><text x="674" y="267">×</text>
    </g>
    <g class="fig-muted" font-size="11">
      <text x="20" y="40">第 1 层（成功 1 次）</text>
      <text x="20" y="94">第 2 层（成功 2 次）</text>
      <text x="20" y="152">第 3 层（成功 3 次）</text>
      <text x="20" y="212">第 4 层（成功 4 / 失败 3）</text>
      <text x="20" y="268">第 5 层（失败 4 次）</text>
    </g>
    <rect class="fig-box-subtle" x="20" y="288" width="662" height="54" rx="6"/>
    <g font-size="11.5" text-anchor="middle">
      <text class="fig-blue" x="351" y="310">圆形（成功 11 个）：ASL_succ = (1×1 + 2×2 + 4×3 + 4×4) / 11 = 33 / 11 = 3</text>
      <text class="fig-orange" x="351" y="330">方形（失败 n + 1 = 12 个）：ASL_fail = (4×3 + 8×4) / 12 = 44 / 12 ≈ 3.67（h = ⌊log₂11⌋ + 1 = 4）</text>
    </g>
  </svg>
  <figcaption>折半查找判定树（n = 11）：圆形为成功结点，补全的 n + 1 个方形外部结点为失败区间</figcaption>
</figure>

> **★考点**：给定 $n$ 个有序元素，画判定树、算 $ASL$、求最大比较次数 $\lfloor \log_2 n\rfloor+1$（$n=11$ 时 $ASL=3$，最多比较 4 次）。

优缺点：效率 $O(\log n)$，优于顺序查找；但要求**有序**（排序本身要花时间）、要求**顺序存储**，插入删除要移动大量元素（平均一半）。

### 分块查找

分块查找又称**索引顺序表查找**，是顺序查找与折半查找的折中。

条件——**分块有序**：把表分成若干块，第 $i$ 块中所有关键字都**小于**第 $i+1$ 块中的最小关键字（等价于各块最大值随块号递增）。**块内可以无序**（更常用，插入删除方便），块间必须有序。

**索引表**：每块记录一项，内容为该块的**最大关键字**和该块的**起始地址**；因为块间有序，索引表本身有序，可折半也可顺序查找。

查找分两步：① 在索引表中确定待查记录属于哪一块；② 在该块内查找（块内有序可折半，无序只能顺序）。

例：18 个元素分 3 块，块最大值依次为 22、48、86；查 38——$38>22$ 且 $38<48$，故在第 2 块，再在块内顺序查找。

$$
ASL_{分块}=ASL_{索引}+ASL_{块内}\approx \log_2\left(\frac{n}{s}+1\right)+\frac{s}{2}
$$

其中 $n$ 为记录总数，$s$ 为每块记录数，索引表共 $n/s$ 项；块内顺序查找平均约 $(s+1)/2$，常近似取 $s/2$。

例：$n=9$，$s=3$——索引表 3 项，$\log_2(3+1)=2$；块内 $3/2=1.5$；$ASL\approx 3.5$。同样 9 个元素：顺序查找 $ASL=5$，折半约 $3.1$，分块恰介于两者之间。


<figure class="cpd-figure not-content" id="wz-w5-fig-3">
  <svg viewBox="0 0 700 246" role="img" aria-labelledby="wz-w5-title-3">
    <title id="wz-w5-title-3">分块查找两步定位：索引表 + 块内顺序查找</title>
    <defs>
      <marker id="wz-w5-arr-3" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <text class="fig-title" x="26" y="22" font-size="12.5">① 索引表（块间有序：max_key 严格递增，支持折半或顺序查）</text>
    <rect class="fig-box" x="32" y="34" width="84" height="32" rx="4"/>
    <rect class="fig-box-accent" x="116" y="34" width="84" height="32" rx="4"/>
    <rect class="fig-box" x="200" y="34" width="84" height="32" rx="4"/>
    <g font-size="12" text-anchor="middle">
      <text class="fig-label" x="74" y="54">22 | 0</text>
      <text class="fig-accent" x="158" y="54">48 | 4</text>
      <text class="fig-label" x="242" y="54">86 | 8</text>
    </g>
    <text class="fig-accent" x="302" y="54" font-size="11.5">查 38：22 &lt; 38 ≤ 48 → 锁定第 2 块（起始下标 4）</text>
    <text class="fig-title" x="26" y="102" font-size="12.5">② 主表（块内可无序，每块元素 ≤ 该块最大关键字）</text>
    <path d="M 158 66 L 158 80 L 254 80 L 254 128" fill="none" stroke="var(--sl-color-accent)" stroke-width="1.5" marker-end="url(#wz-w5-arr-3)"/>
    <g class="fig-box">
      <rect x="32" y="134" width="44" height="32"/><rect x="76" y="134" width="44" height="32"/>
      <rect x="120" y="134" width="44" height="32"/><rect x="164" y="134" width="44" height="32"/>
    </g>
    <rect class="fig-box-blue" x="232" y="134" width="44" height="32"/>
    <rect class="fig-box-blue" x="276" y="134" width="44" height="32"/>
    <rect class="fig-box-green" x="320" y="134" width="44" height="32"/>
    <rect class="fig-box-blue" x="364" y="134" width="44" height="32"/>
    <g class="fig-box">
      <rect x="432" y="134" width="44" height="32"/><rect x="476" y="134" width="44" height="32"/>
      <rect x="520" y="134" width="44" height="32"/><rect x="564" y="134" width="44" height="32"/>
    </g>
    <g font-size="12" text-anchor="middle">
      <text class="fig-label" x="54" y="154">22</text><text class="fig-label" x="98" y="154">12</text><text class="fig-label" x="142" y="154">13</text><text class="fig-label" x="186" y="154">8</text>
      <text class="fig-blue" x="254" y="154">48</text><text class="fig-blue" x="298" y="154">33</text><text class="fig-green" x="342" y="154">38</text><text class="fig-blue" x="386" y="154">24</text>
      <text class="fig-label" x="454" y="154">63</text><text class="fig-label" x="498" y="154">86</text><text class="fig-label" x="542" y="154">51</text><text class="fig-label" x="586" y="154">74</text>
    </g>
    <g class="fig-muted" font-size="10" text-anchor="middle">
      <text x="54" y="126">0</text><text x="98" y="126">1</text><text x="142" y="126">2</text><text x="186" y="126">3</text>
      <text class="fig-accent" x="254" y="126">4</text><text x="298" y="126">5</text><text class="fig-green" x="342" y="126">6</text><text x="386" y="126">7</text>
      <text x="454" y="126">8</text><text x="498" y="126">9</text><text x="542" y="126">10</text><text x="586" y="126">11</text>
    </g>
    <path d="M 254 168 Q 276 184 296 170" fill="none" stroke="var(--sl-color-blue)" stroke-width="1.3" marker-end="url(#wz-w5-arr-3)"/>
    <path d="M 300 168 Q 320 184 340 170" fill="none" stroke="var(--sl-color-green)" stroke-width="1.4" marker-end="url(#wz-w5-arr-3)"/>
    <g class="fig-muted" font-size="11" text-anchor="middle">
      <text x="120" y="198">第 1 块（≤ 22）</text>
      <text class="fig-green" x="320" y="198">第 2 块（22 &lt; x ≤ 48）：48 → 33 → 38 命中</text>
      <text x="520" y="198">第 3 块（48 &lt; x ≤ 86）</text>
      <text x="350" y="226" font-size="11.5">块间有序支持折半/顺序查索引，块内无序支持 O(1) 块尾插入</text>
    </g>
  </svg>
  <figcaption>分块查找示意图：先查索引表定位块始址 4，再在块内沿下标 4 → 5 → 6 顺序比较命中 38</figcaption>
</figure>

> **注意**：精确的块内顺序查找平均为 $(s+1)/2$，$n=9,s=3$ 时 $ASL=2+2=4$；上面的 $3.5$ 是把块内平均近似为 $s/2$ 的常见粗略值，两种写法都要知道。

| 方法 | $ASL$（等概率） | 数量级 | 有序性要求 | 存储结构 | 插入/删除 |
|---|---|---|---|---|---|
| 顺序查找 | $(n+1)/2$ | $O(n)$ | 无要求 | 顺序表或链表 | 方便 |
| 折半查找 | $\approx \log_2(n+1)-1$ | $O(\log n)$ | 必须整体有序 | 只能顺序表 | 需移动元素，麻烦 |
| 分块查找 | $\approx \log_2(n/s+1)+s/2$ | 介于两者之间 | 块间有序、块内可无序 | 顺序表或链表 | 方便（块内无序时） |

分块查找的优点：查找较快，且插入删除只在本块内进行、不需移动大量元素；缺点：要额外增加索引表的存储空间。适合**既要求较快查找、又经常插入删除**的场合。

> **交互演示**：[顺序查找 / 折半查找 / 分块查找](/lab/chapter-9/#lab-binary)

### 二叉排序树的定义与性质

**二叉排序树**（二叉搜索树/二叉查找树，BST）是递归定义的：

- 空树是二叉排序树；
- 非空时：① 若左子树非空，左子树上**所有**结点的值均**小于**根；② 若右子树非空，右子树上所有结点的值均**大于等于**根（等于归右子树）；③ 左、右子树本身也都是二叉排序树。

判定时不能只看局部父子关系，必须看**整棵子树的所有结点**：某结点在左子树里却大于根，或右子树里却有小于根的值，都不是 BST。

存储用二叉链表：`lchild | data（含 key 及其它数据项） | rchild`。

**核心性质**：对二叉排序树做**中序遍历**，得到按关键字**递增有序**的序列（允许相等时相邻）。因此“中序序列是否有序”可作为判定 BST 的依据，建树过程也相当于对无序序列排序。

### 二叉排序树的查找与分析

从根开始，逐层比较：

- 相等 → 查找成功，返回该结点指针；
- `key <` 当前结点 → 只在**左子树**找（右子树全大于根，不可能有）；
- `key >` 当前结点 → 只在**右子树**找；
- 走到**空树** → 查找失败，返回空指针。

```c
BSTNode *SearchBST(BSTree T, KeyType key) {
  if (T == NULL || T->data.key == key) return T;   // 空树失败；相等成功
  if (key < T->data.key) return SearchBST(T->lchild, key);
  return SearchBST(T->rchild, key);
}
```

**过程拆解**：树为 `50(30(20,40), 70(60,80))`。

| 查找/插入 | 路径 | 结果 |
|:---:|:---|:---|
| 查 40 | `40 < 50` 走左到 30 → `40 > 30` 走右到 40 | 命中，比较 3 次 |
| 查 45 | `45 < 50` 左到 30 → `45 > 30` 右到 40 → `45 > 40` 右到空 | 失败，比较 3 次 |
| 插 45 | 沿 50→30→40 走到 40 的右空位 | 45 成为 40 的右孩子 |

比较次数 = 查找路径上经过的结点数 = 该结点**所在层数**，最多等于**树高**。

例：6 个结点、三层分布为 1/2/3 个，则 $ASL=(1\times1+2\times2+3\times3)/6=14/6\approx2.33$；同样 6 个结点若退化成单支（6 层），$ASL=(1+2+\cdots+6)/6=21/6=3.5=(n+1)/2$，与顺序查找相同。

| 形态 | 树高 | 查找复杂度 |
|---|---|---|
| 均衡（接近判定树） | $\approx \log_2 n$ | $O(\log n)$（最好） |
| 单支（插入序列有序） | $n$ | $O(n)$，退化为顺序查找（最坏） |

> **★考点**：BST 的 $ASL$ 与**树的形态**（即关键字插入次序）有关，不是固定值。

<figure class="cpd-figure not-content" id="wz-w5-fig-4">
  <svg viewBox="0 0 700 264" role="img" aria-labelledby="wz-w5-title-4">
    <title id="wz-w5-title-4">二叉排序树（BST）查找/插入路径与树形退化对比</title>
    <defs>
      <marker id="wz-w5-arr-4" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="14" width="384" height="236" rx="8"/>
    <rect class="fig-box-subtle" x="412" y="14" width="272" height="236" rx="8"/>
    <text class="fig-title" x="208" y="34" text-anchor="middle" font-size="12.5">① 均衡 BST：查找 40 与插入 45 路径</text>
    <text class="fig-title" x="548" y="34" text-anchor="middle" font-size="12.5">② 有序插入退化为单支树</text>
    <g class="fig-line">
      <line x1="208" y1="68" x2="128" y2="116"/><line x1="208" y1="68" x2="292" y2="116"/>
      <line x1="128" y1="116" x2="80" y2="164"/><line x1="128" y1="116" x2="176" y2="164"/>
      <line x1="292" y1="116" x2="246" y2="164"/><line x1="292" y1="116" x2="338" y2="164"/>
    </g>
    <path d="M 192 78 L 142 108" fill="none" stroke="var(--sl-color-accent)" stroke-width="1.6" marker-end="url(#wz-w5-arr-4)"/>
    <path d="M 140 128 L 166 154" fill="none" stroke="var(--sl-color-accent)" stroke-width="1.6" marker-end="url(#wz-w5-arr-4)"/>
    <line x1="176" y1="164" x2="212" y2="206" stroke="var(--sl-color-green)" stroke-width="1.5" stroke-dasharray="4 3" marker-end="url(#wz-w5-arr-4)"/>
    <circle class="fig-box-accent" cx="208" cy="68" r="15"/>
    <circle class="fig-box-accent" cx="128" cy="116" r="15"/>
    <circle class="fig-box-blue" cx="292" cy="116" r="15"/>
    <circle class="fig-box-blue" cx="80" cy="164" r="14"/>
    <circle class="fig-box-accent" cx="176" cy="164" r="14"/>
    <circle class="fig-box-blue" cx="246" cy="164" r="14"/>
    <circle class="fig-box-blue" cx="338" cy="164" r="14"/>
    <circle class="fig-box-green" cx="222" cy="214" r="14" stroke-dasharray="3 2"/>
    <g font-size="11.5" text-anchor="middle">
      <text class="fig-accent" x="208" y="72">50</text>
      <text class="fig-accent" x="128" y="120">30</text><text class="fig-blue" x="292" y="120">70</text>
      <text class="fig-blue" x="80" y="168">20</text><text class="fig-accent" x="176" y="168">40</text>
      <text class="fig-blue" x="246" y="168">60</text><text class="fig-blue" x="338" y="168">80</text>
      <text class="fig-green" x="222" y="218">45</text>
    </g>
    <text class="fig-accent" x="146" y="88" font-size="10">&lt;50</text>
    <text class="fig-accent" x="160" y="138" font-size="10">&gt;30</text>
    <text class="fig-green" x="210" y="186" font-size="10">&gt;40 插右空位</text>
    <text class="fig-muted" x="208" y="240" text-anchor="middle" font-size="11">树高平衡：查找/插入 O(log n)，中序得递增序列</text>
    <g class="fig-line">
      <line x1="468" y1="64" x2="500" y2="92"/><line x1="500" y1="92" x2="532" y2="120"/>
      <line x1="532" y1="120" x2="564" y2="148"/><line x1="564" y1="148" x2="596" y2="176"/>
      <line x1="596" y1="176" x2="628" y2="204"/>
    </g>
    <g class="fig-box-red">
      <circle cx="468" cy="64" r="12"/><circle cx="500" cy="92" r="12"/>
      <circle cx="532" cy="120" r="12"/><circle cx="564" cy="148" r="12"/>
      <circle cx="596" cy="176" r="12"/><circle cx="628" cy="204" r="12"/>
    </g>
    <g class="fig-red" font-size="10.5" text-anchor="middle">
      <text x="468" y="68">20</text><text x="500" y="96">30</text>
      <text x="532" y="124">40</text><text x="564" y="152">50</text>
      <text x="596" y="180">60</text><text x="628" y="208">70</text>
    </g>
    <text class="fig-red" x="548" y="228" text-anchor="middle" font-size="11">插入有序 20..70 → 树高 h = n</text>
    <text class="fig-muted" x="548" y="242" text-anchor="middle" font-size="10.5">ASL = (n+1)/2，退化为顺序查找 O(n)</text>
  </svg>
  <figcaption>二叉排序树形态对性能的决定性影响：均衡时为 O(log n)，有序插入退化为单支 O(n)</figcaption>
</figure>

### 二叉排序树的插入与生成

插入规则：先按查找路径走——

- 若树为空：新结点直接作根；
- 若树中已有相同关键字：**不插入**，结束；
- 否则走到某个空指针处，把新结点挂成该叶结点的左孩子或右孩子。

```c
BSTNode *InsertBST(BSTree T, ElemType e) {
  if (T == NULL) { T = malloc(sizeof(BSTNode)); T->data = e;
                   T->lchild = T->rchild = NULL; }
  else if (e.key < T->data.key) T->lchild = InsertBST(T->lchild, e);
  else if (e.key > T->data.key) T->rchild = InsertBST(T->rchild, e);
  return T;                        // 相等：什么也不做
}
```

要点：

- 新结点**一定插在叶子位置**，只修改指针，**不移动其它元素**，代价为查找路径长度。
- **生成** BST：从空树开始，依次插入给定序列即可。
- 例：依次插入 `45, 24, 53, 45, 12, 24, 90`——45 作根，24 为其左孩子，53 为右孩子，12 为 24 的左孩子，90 为 53 的右孩子；重复的 45、24 不插入。
- **插入次序不同，生成的形态不同，查找效率也不同**（如 `40,24,12,37,55` 与 `12,24,37,40,55` 得到两棵形态迥异的 BST）。
- 建树后中序遍历即得有序序列，所以建树过程也可看作排序过程。

### 二叉排序树的删除

删除只删一个结点，但必须保证：删除后仍是二叉排序树（**中序仍有序**），并尽量**不增加树高**。按被删结点的孩子情况分三种：

1. **叶子结点**：直接删除，把双亲对应的孩子指针置空。
2. **只有左子树或只有右子树**：用这唯一的一棵子树**顶替**它——双亲的指针改为指向该子树的根。
3. **左右子树都有**：用它的**中序前驱**（左子树中最大结点）或**中序后继**（右子树中最小结点）的值**替换**它，然后删除那个前驱/后继结点。该结点至多只有一个孩子，必属于情况 1 或 2，递归处理即可。

例：删 45（只有左子树）→ 左孩子顶替；删 78（只有右子树）→ 右孩子顶替；删 78（左右都有）→ 用后继 81 替换 78，再用 88 顶替 81。若改用前驱 65 替换也可行，但树会更高，所以**优先用后继**。

> **★考点**：第 3 种情况先做“值替换”，把问题转化为第 1、2 种，不要真的把整棵子树删掉。

**过程拆解**：删除有两个孩子的根结点 50（树：50 的左子树 30(20,40)，右子树 70(60,80)）。

| 步骤 | 动作 | 结果 |
|:---:|:---|:---|
| 1 | 找 50 的中序后继：右子树最小结点 | 后继为 60 |
| 2 | 用 60 覆盖 50 的值 | 根变为 60 |
| 3 | 删除原 60 结点（它是叶子） | 右子树变为 70(—,80) |

> **注意**：中序后继一定没有左孩子，删除它时只需用其右孩子顶替（也可能为空）。

<figure class="cpd-figure not-content" id="wz-w5-fig-5">
  <svg viewBox="0 0 700 262" role="img" aria-labelledby="wz-w5-title-5">
    <title id="wz-w5-title-5">二叉排序树删除结点的三种情况：叶子、单孩子顶替、双孩子值替换</title>
    <defs>
      <marker id="wz-w5-arr-5" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="14" width="194" height="234" rx="8"/>
    <rect class="fig-box-subtle" x="220" y="14" width="218" height="234" rx="8"/>
    <rect class="fig-box-subtle" x="448" y="14" width="236" height="234" rx="8"/>
    <text class="fig-title" x="113" y="34" text-anchor="middle" font-size="12">① 删叶子结点（删 20）</text>
    <text class="fig-title" x="329" y="34" text-anchor="middle" font-size="12">② 只有一棵子树（删 30）</text>
    <text class="fig-title" x="566" y="34" text-anchor="middle" font-size="12">③ 左右子树都有（删 50）</text>
    <line class="fig-line" x1="113" y1="74" x2="78" y2="124"/>
    <line class="fig-line" x1="113" y1="74" x2="148" y2="124"/>
    <line class="fig-line-dashed" x1="78" y1="124" x2="52" y2="176"/>
    <circle class="fig-box-blue" cx="113" cy="74" r="14"/>
    <circle class="fig-box-blue" cx="78" cy="124" r="14"/>
    <circle class="fig-box-blue" cx="148" cy="124" r="14"/>
    <circle class="fig-box-red" cx="52" cy="176" r="14" stroke-dasharray="3 2"/>
    <g font-size="11.5" text-anchor="middle">
      <text class="fig-blue" x="113" y="78">50</text>
      <text class="fig-blue" x="78" y="128">30</text><text class="fig-blue" x="148" y="128">70</text>
      <text class="fig-red" x="52" y="180">20</text>
    </g>
    <text class="fig-red" x="122" y="180" font-size="10.5">双亲指针置 NULL</text>
    <text class="fig-muted" x="113" y="226" text-anchor="middle" font-size="11">直接释放，不影响其他分支</text>
    <line class="fig-line" x1="312" y1="68" x2="274" y2="112"/>
    <line class="fig-line" x1="312" y1="68" x2="350" y2="112"/>
    <line class="fig-line" x1="274" y1="112" x2="296" y2="156"/>
    <path d="M 312 82 Q 348 118 308 152" fill="none" stroke="var(--sl-color-green)" stroke-width="1.5" marker-end="url(#wz-w5-arr-5)"/>
    <circle class="fig-box-blue" cx="312" cy="68" r="14"/>
    <circle class="fig-box-red" cx="274" cy="112" r="14" stroke-dasharray="3 2"/>
    <circle class="fig-box-blue" cx="350" cy="112" r="14"/>
    <circle class="fig-box-green" cx="296" cy="156" r="14"/>
    <g font-size="11.5" text-anchor="middle">
      <text class="fig-blue" x="312" y="72">50</text>
      <text class="fig-red" x="274" y="116">30</text><text class="fig-blue" x="350" y="116">70</text>
      <text class="fig-green" x="296" y="160">40</text>
    </g>
    <text class="fig-green" x="372" y="156" font-size="10.5">唯一子代</text>
    <text class="fig-green" x="372" y="170" font-size="10.5">直接顶替</text>
    <text class="fig-muted" x="329" y="210" text-anchor="middle" font-size="11">50→lchild 改指 40</text>
    <text class="fig-muted" x="329" y="226" text-anchor="middle" font-size="11">树高减 1，中序仍有序</text>
    <g class="fig-line">
      <line x1="560" y1="68" x2="508" y2="112"/><line x1="560" y1="68" x2="612" y2="112"/>
      <line x1="508" y1="112" x2="484" y2="156"/><line x1="508" y1="112" x2="532" y2="156"/>
      <line x1="612" y1="112" x2="584" y2="156"/><line x1="612" y1="112" x2="640" y2="156"/>
    </g>
    <path d="M 584 140 Q 598 96 574 74" fill="none" stroke="var(--sl-color-accent)" stroke-width="1.6" marker-end="url(#wz-w5-arr-5)"/>
    <circle class="fig-box-accent" cx="560" cy="68" r="15"/>
    <circle class="fig-box-blue" cx="508" cy="112" r="14"/><circle class="fig-box-blue" cx="612" cy="112" r="14"/>
    <circle class="fig-box-blue" cx="484" cy="156" r="13"/><circle class="fig-box-blue" cx="532" cy="156" r="13"/>
    <circle class="fig-box-green" cx="584" cy="156" r="14" stroke-dasharray="3 2"/>
    <circle class="fig-box-blue" cx="640" cy="156" r="13"/>
    <g font-size="11" text-anchor="middle">
      <text class="fig-accent" x="560" y="72">50←60</text>
      <text class="fig-blue" x="508" y="116">30</text><text class="fig-blue" x="612" y="116">70</text>
      <text class="fig-blue" x="484" y="160">20</text><text class="fig-blue" x="532" y="160">40</text>
      <text class="fig-green" x="584" y="160">60</text><text class="fig-blue" x="640" y="160">80</text>
    </g>
    <text class="fig-accent" x="566" y="192" text-anchor="middle" font-size="10.5">① 找右子树最小（中序后继 60）</text>
    <text class="fig-green" x="566" y="210" text-anchor="middle" font-size="10.5">② 值替换根 50 ← 60，再删原 60</text>
    <text class="fig-muted" x="566" y="228" text-anchor="middle" font-size="10.5">（原 60 无左孩，必化归为情况 ① 或 ②）</text>
  </svg>
  <figcaption>二叉排序树三种删除情况：情况 ③ 通过“值替换”转化为情况 ①/②，避免整棵子树重组</figcaption>
</figure>

> **交互演示**：[BST 查找 / 插入 / 删除](/lab/chapter-6/#lab-bstSearch)

### 平衡二叉树的概念与平衡因子

**平衡二叉树**（AVL 树，由 Adelson-Velsky 与 Landis 命名）首先是一棵**二叉排序树**，并额外满足：任一结点的左、右子树**高度之差的绝对值不超过 1**，且左右子树也分别是平衡二叉树。

**平衡因子** $\mathrm{BF}=$ 左子树高度 $-$ 右子树高度，只能取 $-1$、$0$、$1$。逐个结点算出 BF，只要出现 $|\mathrm{BF}|\ge 2$ 就不是 AVL 树。

$n$ 个结点的 AVL 树高度为 $O(\log n)$，故查找、插入、删除均为 $O(\log n)$。

**最少结点数**：高度为 $h$ 的 AVL 树，为使结点最少，根的一棵子树高 $h-1$、另一棵高 $h-2$（高度差恰为 1），于是

$$
N(h)=N(h-1)+N(h-2)+1,\qquad N(1)=1,\ N(2)=2
$$

序列为 $1,2,4,7,12,20,\dots$。反之，$n$ 个结点的 AVL 树高度不超过 $O(\log n)$，这正是它查找性能稳定的原因。

> **注意**：BF 是“高度差”而非“结点数差”；空树高度记 0，单结点高度记 1。

### 平衡调整的四种类型

插入新结点后可能失衡。若同时有多个结点 $|\mathrm{BF}|\ge2$，只调整**最小失衡子树**（离插入点最近的那个失衡结点为根的子树）。

设 $a$ 为失衡结点，$b$ 为 $a$ 的孩子，$c$ 为 $b$ 的孩子（新结点插在 $c$ 的位置），按插入位置分四型：

| 类型 | 插入位置 | 调整操作 | 调整结果 |
|---|---|---|---|
| **LL** | $a$ 的**左**子树的**左**子树 | 对 $a$ **右旋**（顺时针） | $b$ 为根，$a$ 为 $b$ 的右孩子，$b$ 原右子树改作 $a$ 的左子树 |
| **RR** | $a$ 的**右**子树的**右**子树 | 对 $a$ **左旋**（逆时针） | $b$ 为根，$a$ 为 $b$ 的左孩子，$b$ 原左子树改作 $a$ 的右子树 |
| **LR** | $a$ 的**左**子树的**右**子树 | 先对 $b$ 左旋，再对 $a$ 右旋 | $c$ 为根，$b$ 为左孩子，$a$ 为右孩子 |
| **RL** | $a$ 的**右**子树的**左**子树 | 先对 $b$ 右旋，再对 $a$ 左旋 | $c$ 为根，$a$ 为左孩子，$b$ 为右孩子 |

LR 中原 $c$ 的左子树归 $b$ 作右子树、$c$ 的右子树归 $a$ 作左子树；RL 对称（$c$ 的左子树归 $a$ 作右子树、右子树归 $b$ 作左子树）。

统一原则（记不住旋转细节时用它反推）：① 把子树**高度降下来**（三层压成两层）；② 调整后仍满足 BST 性质——三者中**大小居中的做根**，小的在左、大的在右；③ 剩余子树按大小关系挂回原位。

<figure class="cpd-figure not-content" id="wz-w5-fig-6">
  <svg viewBox="0 0 700 416" role="img" aria-labelledby="wz-w5-title-6">
    <title id="wz-w5-title-6">AVL 树四种失衡调整（LL、RR、LR、RL）及子树挂接关系</title>
    <defs>
      <marker id="wz-w5-arr-6" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <line class="fig-divider" x1="350" y1="14" x2="350" y2="402"/>
    <line class="fig-divider" x1="16" y1="208" x2="684" y2="208"/>
    <g class="fig-title" font-size="12.5">
      <text x="24" y="24">LL 型：对 a 右单旋（b 升根，T₂ 挂 a 左）</text>
      <text x="366" y="24">RR 型：对 a 左单旋（b 升根，T₂ 挂 a 右）</text>
      <text x="24" y="228">LR 型：先左旋 b，再右旋 a（c 升根）</text>
      <text x="366" y="228">RL 型：先右旋 b，再左旋 a（c 升根）</text>
    </g>
    <g class="fig-muted" font-size="10.5" text-anchor="middle">
      <text x="86" y="42">失衡前</text><text x="256" y="42">平衡后</text>
      <text x="430" y="42">失衡前</text><text x="600" y="42">平衡后</text>
      <text x="86" y="246">失衡前</text><text x="256" y="246">平衡后</text>
      <text x="430" y="246">失衡前</text><text x="600" y="246">平衡后</text>
    </g>
    <g stroke="var(--sl-color-accent)" stroke-width="1.6" fill="none" marker-end="url(#wz-w5-arr-6)">
      <line x1="154" y1="114" x2="188" y2="114"/>
      <line x1="498" y1="114" x2="532" y2="114"/>
      <line x1="154" y1="318" x2="188" y2="318"/>
      <line x1="498" y1="318" x2="532" y2="318"/>
    </g>
    <g class="fig-line">
      <line x1="86" y1="62" x2="56" y2="104"/><line x1="86" y1="62" x2="118" y2="104"/>
      <line x1="56" y1="104" x2="34" y2="148"/><line x1="56" y1="104" x2="80" y2="148"/>
      <line x1="256" y1="66" x2="220" y2="108"/><line x1="256" y1="66" x2="292" y2="108"/>
      <line x1="292" y1="108" x2="268" y2="148"/><line x1="292" y1="108" x2="316" y2="148"/>
      <line x1="430" y1="62" x2="398" y2="104"/><line x1="430" y1="62" x2="460" y2="104"/>
      <line x1="460" y1="104" x2="436" y2="148"/><line x1="460" y1="104" x2="484" y2="148"/>
      <line x1="600" y1="66" x2="564" y2="108"/><line x1="600" y1="66" x2="636" y2="108"/>
      <line x1="564" y1="108" x2="540" y2="148"/><line x1="564" y1="108" x2="588" y2="148"/>
      <line x1="86" y1="266" x2="56" y2="308"/><line x1="86" y1="266" x2="118" y2="308"/>
      <line x1="56" y1="308" x2="34" y2="352"/><line x1="56" y1="308" x2="86" y2="352"/>
      <line x1="256" y1="270" x2="220" y2="312"/><line x1="256" y1="270" x2="292" y2="312"/>
      <line x1="220" y1="312" x2="202" y2="356"/><line x1="220" y1="312" x2="242" y2="356"/>
      <line x1="292" y1="312" x2="270" y2="356"/><line x1="292" y1="312" x2="310" y2="356"/>
      <line x1="430" y1="266" x2="398" y2="308"/><line x1="430" y1="266" x2="460" y2="308"/>
      <line x1="460" y1="308" x2="430" y2="352"/><line x1="460" y1="308" x2="484" y2="352"/>
      <line x1="600" y1="270" x2="564" y2="312"/><line x1="600" y1="270" x2="636" y2="312"/>
      <line x1="564" y1="312" x2="546" y2="356"/><line x1="564" y1="312" x2="586" y2="356"/>
      <line x1="636" y1="312" x2="614" y2="356"/><line x1="636" y1="312" x2="654" y2="356"/>
    </g>
    <g class="fig-box">
      <polygon points="118,96 106,120 130,120"/><polygon points="80,140 68,164 92,164"/>
      <polygon points="268,140 256,164 280,164"/><polygon points="316,140 304,164 328,164"/>
      <polygon points="398,96 386,120 410,120"/><polygon points="436,140 424,164 448,164"/>
      <polygon points="540,140 528,164 552,164"/><polygon points="588,140 576,164 600,164"/>
      <polygon points="118,300 106,324 130,324"/><polygon points="34,344 22,368 46,368"/>
      <polygon points="202,350 192,372 212,372"/><polygon points="242,350 232,372 252,372"/>
      <polygon points="270,350 260,372 280,372"/><polygon points="310,350 300,372 320,372"/>
      <polygon points="398,300 386,324 410,324"/><polygon points="484,344 472,368 496,368"/>
      <polygon points="546,350 536,372 556,372"/><polygon points="586,350 576,372 596,372"/>
      <polygon points="614,350 604,372 624,372"/><polygon points="654,350 644,372 664,372"/>
    </g>
    <circle class="fig-box-red" cx="86" cy="62" r="12"/><circle class="fig-box-blue" cx="56" cy="104" r="12"/><circle class="fig-box-green" cx="34" cy="148" r="12"/>
    <circle class="fig-box-green" cx="256" cy="66" r="12"/><circle class="fig-box-blue" cx="220" cy="108" r="12"/><circle class="fig-box-blue" cx="292" cy="108" r="12"/>
    <circle class="fig-box-red" cx="430" cy="62" r="12"/><circle class="fig-box-blue" cx="460" cy="104" r="12"/><circle class="fig-box-green" cx="484" cy="148" r="12"/>
    <circle class="fig-box-green" cx="600" cy="66" r="12"/><circle class="fig-box-blue" cx="564" cy="108" r="12"/><circle class="fig-box-blue" cx="636" cy="108" r="12"/>
    <circle class="fig-box-red" cx="86" cy="266" r="12"/><circle class="fig-box-blue" cx="56" cy="308" r="12"/><circle class="fig-box-green" cx="86" cy="352" r="12"/>
    <circle class="fig-box-green" cx="256" cy="270" r="12"/><circle class="fig-box-blue" cx="220" cy="312" r="12"/><circle class="fig-box-blue" cx="292" cy="312" r="12"/>
    <circle class="fig-box-red" cx="430" cy="266" r="12"/><circle class="fig-box-blue" cx="460" cy="308" r="12"/><circle class="fig-box-green" cx="430" cy="352" r="12"/>
    <circle class="fig-box-green" cx="600" cy="270" r="12"/><circle class="fig-box-blue" cx="564" cy="312" r="12"/><circle class="fig-box-blue" cx="636" cy="312" r="12"/>
    <g font-size="11.5" text-anchor="middle">
      <text class="fig-red" x="86" y="66">a</text><text class="fig-blue" x="56" y="108">b</text><text class="fig-green" x="34" y="152">c</text>
      <text class="fig-green" x="256" y="70">b</text><text class="fig-blue" x="220" y="112">c</text><text class="fig-blue" x="292" y="112">a</text>
      <text class="fig-red" x="430" y="66">a</text><text class="fig-blue" x="460" y="108">b</text><text class="fig-green" x="484" y="152">c</text>
      <text class="fig-green" x="600" y="70">b</text><text class="fig-blue" x="564" y="112">a</text><text class="fig-blue" x="636" y="112">c</text>
      <text class="fig-red" x="86" y="270">a</text><text class="fig-blue" x="56" y="312">b</text><text class="fig-green" x="86" y="356">c</text>
      <text class="fig-green" x="256" y="274">c</text><text class="fig-blue" x="220" y="316">b</text><text class="fig-blue" x="292" y="316">a</text>
      <text class="fig-red" x="430" y="270">a</text><text class="fig-blue" x="460" y="312">b</text><text class="fig-green" x="430" y="356">c</text>
      <text class="fig-green" x="600" y="274">c</text><text class="fig-blue" x="564" y="316">a</text><text class="fig-blue" x="636" y="316">b</text>
    </g>
    <g class="fig-muted" font-size="9.5" text-anchor="middle">
      <text x="118" y="116">T₃</text><text x="80" y="160">T₂</text><text x="268" y="160">T₂</text><text x="316" y="160">T₃</text>
      <text x="398" y="116">T₁</text><text x="436" y="160">T₂</text><text x="540" y="160">T₁</text><text x="588" y="160">T₂</text>
      <text x="118" y="320">T₄</text><text x="34" y="364">T₁</text>
      <text x="202" y="368">T₁</text><text x="242" y="368">T₂</text><text x="270" y="368">T₃</text><text x="310" y="368">T₄</text>
      <text x="398" y="320">T₁</text><text x="484" y="364">T₄</text>
      <text x="546" y="368">T₁</text><text x="586" y="368">T₂</text><text x="614" y="368">T₃</text><text x="654" y="368">T₄</text>
      <text class="fig-red" x="118" y="66">BF=+2</text><text class="fig-red" x="462" y="66">BF=−2</text>
      <text class="fig-red" x="118" y="270">BF=+2</text><text class="fig-red" x="462" y="270">BF=−2</text>
      <text x="175" y="192" font-size="10.5">居中结点 b 升根；b 原右子树 T₂ 改作 a 左子树</text>
      <text x="525" y="192" font-size="10.5">居中结点 b 升根；b 原左子树 T₂ 改作 a 右子树</text>
      <text x="175" y="394" font-size="10.5">居中结点 c 升根；c 的左右子树 T₂、T₃ 分挂 b 右与 a 左</text>
      <text x="525" y="394" font-size="10.5">居中结点 c 升根；c 的左右子树 T₂、T₃ 分挂 a 右与 b 左</text>
    </g>
  </svg>
  <figcaption>AVL 四种平衡旋转通则：将大小居中的结点（绿色）提为新根，其余子树按大小顺序挂回原空位</figcaption>
</figure>

**构造例题**：依次插入 `16, 3, 7, 11, 9, 26, 18, 14, 15`。

| 步骤 | 插入 | 现象 | 调整 |
|---|---|---|---|
| 1–2 | 16, 3 | 平衡 | — |
| 3 | 7 | 16 的 BF $=2$ | LR：7 上升，3、16 为其左右孩子 |
| 4–5 | 11, 9 | 16 的 BF $=2$（9 在 11 左侧；7 也失衡，取最小子树 16） | LL：11 上升，9、16 为其左右孩子 |
| 6 | 26 | 7 的 BF $=-2$（26 在右右） | RR：11 上升，7 左、16 右（11 原左子树 9 转为 7 的右子树） |
| 7 | 18 | 16 的 BF $=-2$（18 在 26 左侧） | RL：18 上升，16 左、26 右 |
| 8 | 14 | 平衡 | — |
| 9 | 15 | 16、18、11 三个结点失衡，调最小子树（根 16） | LR：15 上升，14 左、16 右 |

最终得到：

```
          11
        /    \
       7      18
      / \    /  \
     3   9  15   26
           /  \
          14  16
```

最终各结点 BF：根 11 为 $-1$、18 为 $+1$，其余全为 $0$（均在 $\pm1$ 内），构造完成。注意第 9 步必须选**最小失衡子树**（3 个结点的 16-14-15），而不是从整棵树的根开始转。

<figure class="cpd-figure not-content" id="wz-w5-fig-7">
  <svg viewBox="0 0 700 328" role="img" aria-labelledby="wz-w5-title-7">
    <title id="wz-w5-title-7">AVL 树构造例题分步演进：16, 3, 7, 11, 9, 26, 18, 14, 15</title>
    <defs>
      <marker id="wz-w5-arr-7" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <rect class="fig-box-subtle" x="16" y="14" width="212" height="142" rx="6"/>
    <rect class="fig-box-subtle" x="244" y="14" width="212" height="142" rx="6"/>
    <rect class="fig-box-subtle" x="472" y="14" width="212" height="142" rx="6"/>
    <rect class="fig-box-subtle" x="16" y="168" width="322" height="146" rx="6"/>
    <rect class="fig-box-subtle" x="354" y="168" width="330" height="146" rx="6"/>
    <text class="fig-title" x="122" y="32" text-anchor="middle" font-size="11.5">第 3 步插 7：LR 型 → 7 升根</text>
    <text class="fig-title" x="350" y="32" text-anchor="middle" font-size="11.5">第 5 步插 9：LL 型调子树 16</text>
    <text class="fig-title" x="578" y="32" text-anchor="middle" font-size="11.5">第 6 步插 26：RR 型调根 7</text>
    <text class="fig-title" x="177" y="186" text-anchor="middle" font-size="11.5">第 7 步插 18：RL 型调子树 16 → 18 升</text>
    <text class="fig-title" x="519" y="186" text-anchor="middle" font-size="11.5">第 9 步插 15：LR 型调最小子树 16（终态）</text>
    <g class="fig-line">
      <line x1="66" y1="56" x2="44" y2="88"/><line x1="44" y1="88" x2="66" y2="120"/>
      <line x1="168" y1="64" x2="140" y2="104"/><line x1="168" y1="64" x2="196" y2="104"/>
      <line x1="296" y1="54" x2="268" y2="86"/><line x1="296" y1="54" x2="324" y2="86"/>
      <line x1="324" y1="86" x2="302" y2="114"/><line x1="302" y1="114" x2="286" y2="138"/>
      <line x1="406" y1="54" x2="378" y2="86"/><line x1="406" y1="54" x2="430" y2="86"/>
      <line x1="430" y1="86" x2="412" y2="122"/><line x1="430" y1="86" x2="446" y2="122"/>
      <line x1="568" y1="56" x2="528" y2="90"/><line x1="568" y1="56" x2="608" y2="90"/>
      <line x1="528" y1="90" x2="504" y2="128"/><line x1="528" y1="90" x2="552" y2="128"/>
      <line x1="608" y1="90" x2="634" y2="128"/>
      <line x1="162" y1="210" x2="110" y2="244"/><line x1="162" y1="210" x2="214" y2="244"/>
      <line x1="110" y1="244" x2="84" y2="282"/><line x1="110" y1="244" x2="136" y2="282"/>
      <line x1="214" y1="244" x2="188" y2="282"/><line x1="214" y1="244" x2="240" y2="282"/>
      <line x1="500" y1="210" x2="444" y2="240"/><line x1="500" y1="210" x2="556" y2="240"/>
      <line x1="444" y1="240" x2="416" y2="274"/><line x1="444" y1="240" x2="472" y2="274"/>
      <line x1="556" y1="240" x2="528" y2="274"/><line x1="556" y1="240" x2="584" y2="274"/>
      <line x1="528" y1="274" x2="506" y2="300"/><line x1="528" y1="274" x2="550" y2="300"/>
    </g>
    <line class="fig-line-accent" x1="86" y1="88" x2="116" y2="88" marker-end="url(#wz-w5-arr-7)"/>
    <line class="fig-line-accent" x1="340" y1="88" x2="366" y2="88" marker-end="url(#wz-w5-arr-7)"/>
    <circle class="fig-box-red" cx="66" cy="56" r="11"/><circle class="fig-box-blue" cx="44" cy="88" r="11"/><circle class="fig-box-green" cx="66" cy="120" r="11"/>
    <circle class="fig-box-green" cx="168" cy="64" r="12"/><circle class="fig-box-blue" cx="140" cy="104" r="11"/><circle class="fig-box-blue" cx="196" cy="104" r="11"/>
    <circle class="fig-box-blue" cx="296" cy="54" r="10"/><circle class="fig-box-blue" cx="268" cy="86" r="10"/><circle class="fig-box-red" cx="324" cy="86" r="10"/>
    <circle class="fig-box-blue" cx="302" cy="114" r="10"/><circle class="fig-box-green" cx="286" cy="138" r="10"/>
    <circle class="fig-box-blue" cx="406" cy="54" r="10"/><circle class="fig-box-blue" cx="378" cy="86" r="10"/><circle class="fig-box-green" cx="430" cy="86" r="10"/>
    <circle class="fig-box-blue" cx="412" cy="122" r="10"/><circle class="fig-box-blue" cx="446" cy="122" r="10"/>
    <circle class="fig-box-green" cx="568" cy="56" r="11"/><circle class="fig-box-blue" cx="528" cy="90" r="11"/><circle class="fig-box-blue" cx="608" cy="90" r="11"/>
    <circle class="fig-box-blue" cx="504" cy="128" r="10"/><circle class="fig-box-orange" cx="552" cy="128" r="10"/><circle class="fig-box-blue" cx="634" cy="128" r="10"/>
    <circle class="fig-box-blue" cx="162" cy="210" r="11"/><circle class="fig-box-blue" cx="110" cy="244" r="11"/><circle class="fig-box-green" cx="214" cy="244" r="11"/>
    <circle class="fig-box-blue" cx="84" cy="282" r="10"/><circle class="fig-box-blue" cx="136" cy="282" r="10"/><circle class="fig-box-blue" cx="188" cy="282" r="10"/><circle class="fig-box-blue" cx="240" cy="282" r="10"/>
    <circle class="fig-box-accent" cx="500" cy="210" r="11"/><circle class="fig-box-blue" cx="444" cy="240" r="11"/><circle class="fig-box-blue" cx="556" cy="240" r="11"/>
    <circle class="fig-box-blue" cx="416" cy="274" r="10"/><circle class="fig-box-blue" cx="472" cy="274" r="10"/><circle class="fig-box-green" cx="528" cy="274" r="10"/><circle class="fig-box-blue" cx="584" cy="274" r="10"/>
    <circle class="fig-box-blue" cx="506" cy="300" r="10"/><circle class="fig-box-blue" cx="550" cy="300" r="10"/>
    <g font-size="10" text-anchor="middle">
      <text class="fig-red" x="66" y="60">16</text><text class="fig-blue" x="44" y="92">3</text><text class="fig-green" x="66" y="124">7</text>
      <text class="fig-green" x="168" y="68">7</text><text class="fig-blue" x="140" y="108">3</text><text class="fig-blue" x="196" y="108">16</text>
      <text class="fig-blue" x="296" y="58">7</text><text class="fig-blue" x="268" y="90">3</text><text class="fig-red" x="324" y="90">16</text>
      <text class="fig-blue" x="302" y="118">11</text><text class="fig-green" x="286" y="142">9</text>
      <text class="fig-blue" x="406" y="58">7</text><text class="fig-blue" x="378" y="90">3</text><text class="fig-green" x="430" y="90">11</text>
      <text class="fig-blue" x="412" y="126">9</text><text class="fig-blue" x="446" y="126">16</text>
      <text class="fig-green" x="568" y="60">11</text><text class="fig-blue" x="528" y="94">7</text><text class="fig-blue" x="608" y="94">16</text>
      <text class="fig-blue" x="504" y="132">3</text><text class="fig-orange" x="552" y="132">9</text><text class="fig-blue" x="634" y="132">26</text>
      <text class="fig-blue" x="162" y="214">11</text><text class="fig-blue" x="110" y="248">7</text><text class="fig-green" x="214" y="248">18</text>
      <text class="fig-blue" x="84" y="286">3</text><text class="fig-blue" x="136" y="286">9</text><text class="fig-blue" x="188" y="286">16</text><text class="fig-blue" x="240" y="286">26</text>
      <text class="fig-accent" x="500" y="214">11</text><text class="fig-blue" x="444" y="244">7</text><text class="fig-blue" x="556" y="244">18</text>
      <text class="fig-blue" x="416" y="278">3</text><text class="fig-blue" x="472" y="278">9</text><text class="fig-green" x="528" y="278">15</text><text class="fig-blue" x="584" y="278">26</text>
      <text class="fig-blue" x="506" y="304">14</text><text class="fig-blue" x="550" y="304">16</text>
    </g>
    <text class="fig-orange" x="578" y="148" text-anchor="middle" font-size="10">原 11 左子 9 改挂 7 右</text>
    <text class="fig-muted" x="288" y="276" text-anchor="middle" font-size="10">16-26-18 → RL</text>
    <text class="fig-accent" x="530" y="206" font-size="9.5">BF=−1</text>
    <text class="fig-blue" x="586" y="236" font-size="9.5">BF=+1</text>
    <text class="fig-muted" x="634" y="278" text-anchor="middle" font-size="10">16-14-15 → LR</text>
  </svg>
  <figcaption>AVL 树构造例题 5 次关键失衡调整轨迹：每次仅调整离新结点最近的最小失衡子树</figcaption>
</figure>

> **交互演示**：[AVL 插入与四种旋转](/lab/chapter-6/#lab-avlInsert)

### 散列表的基本概念与散列函数

**散列存储**：不按输入顺序、也不按大小排序，而是由关键字值**直接计算**存储地址。对应关系 $H(key)$ 称为**散列函数（哈希函数）**，按它建立的表称**散列表（哈希表）**。

- 例：取学号后两位作地址（末两位是 11 就存 11 号单元）；或直接 $H(k)=k$，则 21 存 21 号、39 存 39 号。
- **冲突**：$key_1\neq key_2$ 但 $H(key_1)=H(key_2)$，即不同关键字算出同一地址。
- **同义词**：映射到同一散列地址的那些关键字互称同义词（如 $k\bmod 7$ 下 25、39、11 的余数都是 4）。

冲突**不可能完全避免**，只能尽量减少；散列法要解决两个问题：构造合适的散列函数、设计处理冲突的方法。

理想的散列查找是 $O(1)$——算一次地址就能定位；缺点是**空间效率低**（如 6 个元素占 39 个单元）。散列法本质是**用空间换时间**。

构造散列函数要考虑：函数本身简单（计算快）、关键字长度、散列表长度、关键字分布、查找频率。

- **直接定址法**：$H(k)=a\cdot k+b$。关键字与地址一一对应，**不会冲突**；但地址必须连续，空隙多时浪费空间。
- **除留余数法**（最常用）：$H(k)=k \bmod p$，$p$ 取**小于等于表长的质数**，散列效果较好。
- 其它方法（数字分析法、平方取中法、折叠法、随机数法）只需了解。

### 处理冲突的方法

**开放定址法**（开地址法）：所有地址开放，冲突时按增量序列去找下一个空地址：

$$
H_i=(H(k)+d_i)\bmod m
$$

- **线性探测法**：$d_i=1,2,3,\dots$，冲突就往后逐个试，直到找到空单元。
- **二次探测法**：$d_i=1^2,-1^2,2^2,-2^2,\dots$，即 $+1,-1,+4,-4,\dots$，在两侧跳跃，可减轻聚集。
- **伪随机探测法**：$d_i$ 为一串伪随机数，下一个位置无规律，由随机序列决定。

线性探测例：表长 11，$H(k)=k\bmod 11$，依次插入 `47, 7, 29, 11, 16, 92, 22, 8, 3`。

| 关键字 | 47 | 7 | 29 | 11 | 16 | 92 | 22 | 8 | 3 |
|---|---|---|---|---|---|---|---|---|---|
| 散列地址 | 3 | 7 | 7→8 | 0 | 5 | 4 | 0→1 | 8→9 | 3→4→5→6 |
| 比较次数 | 1 | 1 | 2 | 1 | 1 | 1 | 2 | 2 | 4 |

$$
ASL=\frac{1+1+2+1+1+1+2+2+4}{9}=\frac{15}{9}\approx1.67
$$

线性探测的缺点是产生**聚集**：本非同义词的元素被挤到相邻位置，后续查找、插入都要多探测，冲突连锁增加。

**链地址法**（拉链法）：把所有散列地址相同的记录链成**一个单链表**，再用一个数组存放 $m$ 个链表的头指针（$m$ 为散列地址个数），形成动态的散列表。

- 建立：算出地址；该链表为空则直接挂入，非空则用头插/尾插把新结点插入链表。
- 优点：**非同义词不会冲突**（没有聚集）；链表结点动态申请，表长不定时也方便；插入删除方便。

> **注意**：开放定址法中删除元素不能简单置空，否则会截断后续同义词的探测链；链地址法则无此问题。

<figure class="cpd-figure not-content" id="wz-w5-fig-8">
  <svg viewBox="0 0 700 288" role="img" aria-labelledby="wz-w5-title-8">
    <title id="wz-w5-title-8">散列冲突处理对比：线性探测聚集 vs 链地址法拉链</title>
    <defs>
      <marker id="wz-w5-arr-8" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <text class="fig-title" x="24" y="22" font-size="12.5">一、线性探测（m = 11，H(k) = k mod 11）：非同义词占坑引发“聚集”</text>
    <path d="M 224 44 Q 252 28 278 44" fill="none" stroke="var(--sl-color-orange)" stroke-width="1.3" marker-end="url(#wz-w5-arr-8)"/>
    <path d="M 282 44 Q 308 28 334 44" fill="none" stroke="var(--sl-color-orange)" stroke-width="1.3" marker-end="url(#wz-w5-arr-8)"/>
    <path d="M 338 44 Q 364 28 390 44" fill="none" stroke="var(--sl-color-orange)" stroke-width="1.3" marker-end="url(#wz-w5-arr-8)"/>
    <text class="fig-orange" x="308" y="34" text-anchor="middle" font-size="10">插 3（3 mod 11=3）：连撞 3 次落 6</text>
    <rect class="fig-box" x="26" y="48" width="58" height="30"/>
    <rect class="fig-box" x="84" y="48" width="58" height="30"/>
    <rect class="fig-box" x="142" y="48" width="58" height="30"/>
    <rect class="fig-box-orange" x="200" y="48" width="58" height="30"/>
    <rect class="fig-box-orange" x="258" y="48" width="58" height="30"/>
    <rect class="fig-box-orange" x="316" y="48" width="58" height="30"/>
    <rect class="fig-box-orange" x="374" y="48" width="58" height="30"/>
    <rect class="fig-box-blue" x="432" y="48" width="58" height="30"/>
    <rect class="fig-box-blue" x="490" y="48" width="58" height="30"/>
    <rect class="fig-box-blue" x="548" y="48" width="58" height="30"/>
    <rect class="fig-box" x="606" y="48" width="58" height="30"/>
    <g font-size="12" text-anchor="middle">
      <text class="fig-label" x="55" y="67">11</text><text class="fig-label" x="113" y="67">22</text>
      <text class="fig-muted" x="171" y="67">—</text><text class="fig-orange" x="229" y="67">47</text>
      <text class="fig-orange" x="287" y="67">92</text><text class="fig-orange" x="345" y="67">16</text>
      <text class="fig-orange" x="403" y="67">3</text><text class="fig-blue" x="461" y="67">7</text>
      <text class="fig-blue" x="519" y="67">29</text><text class="fig-blue" x="577" y="67">8</text>
      <text class="fig-muted" x="635" y="67">—</text>
    </g>
    <g class="fig-muted" font-size="10.5" text-anchor="middle">
      <text x="55" y="92">0</text><text x="113" y="92">1</text><text x="171" y="92">2</text>
      <text x="229" y="92">3</text><text x="287" y="92">4</text><text x="345" y="92">5</text>
      <text x="403" y="92">6</text><text x="461" y="92">7</text><text x="519" y="92">8</text>
      <text x="577" y="92">9</text><text x="635" y="92">10</text>
    </g>
    <line class="fig-divider" x1="24" y1="108" x2="676" y2="108"/>
    <text class="fig-title" x="24" y="128" font-size="12.5">二、链地址法（拉链法）：同义词挂入同一链表，非同义词绝不冲突</text>
    <g class="fig-box">
      <rect x="26" y="142" width="54" height="22"/><rect x="26" y="164" width="54" height="22"/>
      <rect x="26" y="186" width="54" height="22"/><rect x="26" y="208" width="54" height="22"/>
      <rect x="26" y="230" width="54" height="22"/><rect x="26" y="252" width="54" height="22"/>
    </g>
    <g class="fig-muted" font-size="11" text-anchor="middle">
      <text x="53" y="157">0</text><text x="53" y="179">3</text>
      <text x="53" y="201">4</text><text x="53" y="223">5</text>
      <text x="53" y="245">7</text><text x="53" y="267">8</text>
    </g>
    <g stroke="var(--sl-color-accent)" stroke-width="1.3" fill="none" marker-end="url(#wz-w5-arr-8)">
      <line x1="80" y1="153" x2="112" y2="153"/><line x1="176" y1="153" x2="208" y2="153"/>
      <line x1="80" y1="175" x2="112" y2="175"/><line x1="176" y1="175" x2="208" y2="175"/>
      <line x1="80" y1="197" x2="112" y2="197"/>
      <line x1="80" y1="219" x2="112" y2="219"/>
      <line x1="80" y1="241" x2="112" y2="241"/><line x1="176" y1="241" x2="208" y2="241"/>
      <line x1="80" y1="263" x2="112" y2="263"/>
    </g>
    <g class="fig-box-green">
      <rect x="116" y="143" width="60" height="20" rx="4"/><rect x="212" y="143" width="60" height="20" rx="4"/>
      <rect x="116" y="165" width="60" height="20" rx="4"/><rect x="212" y="165" width="60" height="20" rx="4"/>
      <rect x="116" y="187" width="60" height="20" rx="4"/>
      <rect x="116" y="209" width="60" height="20" rx="4"/>
      <rect x="116" y="231" width="60" height="20" rx="4"/><rect x="212" y="231" width="60" height="20" rx="4"/>
      <rect x="116" y="253" width="60" height="20" rx="4"/>
    </g>
    <g class="fig-green" font-size="11" text-anchor="middle">
      <text x="146" y="157">11</text><text x="242" y="157">22 ∧</text>
      <text x="146" y="179">47</text><text x="242" y="179">3 ∧</text>
      <text x="146" y="201">92 ∧</text>
      <text x="146" y="223">16 ∧</text>
      <text x="146" y="245">7</text><text x="242" y="245">29 ∧</text>
      <text x="146" y="267">8 ∧</text>
    </g>
    <rect class="fig-box-subtle" x="308" y="154" width="368" height="106" rx="6"/>
    <g font-size="11.5">
      <text class="fig-title" x="324" y="178">链地址法优势（ASL ≈ 1 + α/2）：</text>
      <text class="fig-muted" x="324" y="200">1. 非同义词绝不互相占坑，彻底消除“聚集”现象</text>
      <text class="fig-muted" x="324" y="220">2. 表长不固定时可动态申请结点，适合频繁插入</text>
      <text class="fig-muted" x="324" y="240">3. 删除可直接摘链释放，不会截断后续探测链</text>
    </g>
  </svg>
  <figcaption>开放定址法（线性探测聚集 3→4→5→6）与链地址法（各散列桶独立拉链）对比</figcaption>
</figure>

### 散列表的查找与性能分析

查找过程与建表过程一致：先算 $H(key)$，到该地址比较——相等则成功；不等则按**建表时同样的探测序列**（或同一链表）继续找；一旦遇到**空地址**（或链表走完）即失败。

例：12 个关键字，$H(k)=k\bmod 13$，表长 16，线性探测建表：

| 下标 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
| 记录 | — | 14 | 1 | 68 | 27 | 55 | 19 | 20 |

| 下标 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 |
|---|---|---|---|---|---|---|---|---|
| 记录 | 84 | 79 | 23 | 11 | 10 | — | — | — |

各关键字比较次数：19、14、23、68、20、11 各 1 次；1 为 2 次；84、55、10 各 3 次；27 为 4 次；79 为 9 次（连续探测 9 个位置）。

$$
ASL_{线性探测}=\frac{6\times1+1\times2+3\times3+1\times4+1\times9}{12}=\frac{30}{12}=2.5
$$

改用**链地址法**存同一组关键字，各链长度为 4、2、2、1、2、1，按尾插次序比较：6 个元素 1 次、4 个元素 2 次、1 个 3 次、1 个 4 次：

$$
ASL_{链地址}=\frac{6\times1+4\times2+1\times3+1\times4}{12}=\frac{21}{12}=1.75
$$

对比：无序表顺序查找 $ASL=(12+1)/2=6.5$；有序表折半查找约 $\log_2 13-1\approx2.7$。散列法在平均情况下明显更优。

**装填因子**：$\alpha=\dfrac{n}{m}$（表中记录数 / 散列表长度），上例 $\alpha=12/16=0.75$。

$ASL$ 取决于三个因素：**散列函数**、**处理冲突的方法**、**装填因子**。$\alpha$ 越大表越满、冲突越多、$ASL$ 越大；$\alpha$ 越小则空间浪费。链地址法近似 $ASL\approx 1+\alpha/2$，其他方法也随 $\alpha$ 单调上升。

> **★考点**：散列表的平均查找长度**不是严格的 $O(1)$**，它由装填因子和冲突处理方法决定；只有冲突很少时才接近 $O(1)$，最坏（全部同义词）退化为 $O(n)$。

结论：① 散列法平均查找性能优于折半查找；② **链地址法优于开放定址法**（无聚集、动态、便于插入删除）；③ 散列函数优先用除留余数法，除数取小于等于表长的质数。

> **交互演示**：[散列表线性探测 / 平方探测 / 链地址法](/lab/chapter-9/#lab-hash_linear)

## 第8章 排序

### 排序的基本概念与存储结构

**排序**：把一组杂乱无章的数据记录，按关键字重新排列成有序序列。可以是升序也可以是降序，本章统一讨论**从小到大**，降序同理。

- 排序**针对的是关键字**（记录中的某一个数据域），不是整条记录。一条学生记录含学号、姓名、班级、专业、各科分数、总分等多个域，说“按姓名排序”，就是拿姓名字段作关键字。
- **直接应用**：文件资源管理器按名称 / 修改日期 / 类型 / 大小排序；数据处理软件按单关键字或多关键字排序；购物网站按好评、销量、出版时间排序；游戏排行榜。
- **间接应用**：上一章的**折半查找**要求表必须有序；图的最短路径、最小生成树要按边的权值排序。所以排序几乎出现在所有软件中。

> **★考点**：比较的是**关键字**，搬动的是**整条记录**；同一关键字值可能对应多条记录，这正是“稳定性”存在的理由。

课程中所有算法统一在**顺序表**上实现，下标从 1 开始、`r[0]` 留作辅助单元：

```c
#define MAXSIZE 1000            /* 元素个数上限，可按需调整 */
typedef int KeyType;            /* 关键字统一按整型处理 */
typedef struct {
    KeyType key;                /* 关键字 */
    /* 其他数据项：姓名、各科成绩、总分……按需扩充 */
} RecordType;

typedef struct {
    RecordType r[MAXSIZE + 1];  /* r[1..n] 存记录，r[0] 作哨兵/暂存 */
    int length;                 /* 当前表长 n */
} SqList;
```

多开的这个 `r[0]` 有两个用途：**插入类排序**把它当哨兵，省掉“下标是否越界”的判断；**快速排序**用它暂存枢轴。下标 1..n 与完全二叉树的层序编号一一对应，堆排序可以直接套用二叉树性质。

### 排序方法的分类

| 划分依据 | 类别 | 含义 |
| --- | --- | --- |
| 存储介质 | **内部排序** | 数据量不大，全在内存中完成，不与外存交换 |
|  | **外部排序** | 数据量在内存放不下，分批调入内存排序，中间结果写回外存 |
| 比较器个数 | **串行排序** | 单处理器，同一时刻只能比较一对元素 |
|  | **并行排序** | 多处理器，同一时刻可比较多对元素 |
| 主要操作 | **比较排序** | 靠比较关键字大小定序：插入、交换、选择、归并 |
|  | **基数排序** | 不比较大小，按关键字各位的取值分配、收集 |
| 辅助空间 | **原地排序** | 辅助空间为 $O(1)$，与元素个数无关 |
|  | **非原地排序** | 辅助空间超过 $O(1)$，随元素个数增长 |
| 稳定性 | **稳定排序** / **不稳定排序** | 见下一节 |
| 自然性 | **自然排序** | 初始序列越有序，排得越快 |
|  | **非自然排序** | 初始越有序反而越慢（快速排序就是典型） |

课程研究范围：**内部排序 + 串行排序**，既有基于比较的各类算法，也有不基于比较的基数排序。

按工作量还能粗分三档：$O(n^2)$ 的简单排序（直接插入、冒泡、简单选择）、$O(n\log n)$ 的先进排序（快速、堆、归并）、线性阶的基数排序。

> **注意**：分类维度彼此独立，同一个算法会同时落在好几个类别里，例如直接插入排序 = 内部 + 串行 + 比较 + 原地 + 稳定 + 自然排序。

<figure class="cpd-figure not-content" id="wz-w5-fig-9">
  <svg viewBox="0 0 700 258" role="img" aria-labelledby="wz-w5-title-9">
    <title id="wz-w5-title-9">四类排序方法核心操作直观对比</title>
    <defs>
      <marker id="wz-w5-arr-9" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <line class="fig-divider" x1="350" y1="14" x2="350" y2="244"/>
    <line class="fig-divider" x1="16" y1="126" x2="684" y2="126"/>
    <text class="fig-title" x="24" y="24" font-size="12.5">冒泡：相邻逆序交换（每趟最大值沉底）</text>
    <text class="fig-title" x="366" y="24" font-size="12.5">希尔：按增量 d = 3 分组插排</text>
    <rect class="fig-box-blue" x="24" y="42" width="42" height="28" rx="4"/>
    <rect class="fig-box-blue" x="72" y="42" width="42" height="28" rx="4"/>
    <rect class="fig-box-orange" x="120" y="42" width="42" height="28" rx="4"/>
    <rect class="fig-box-orange" x="168" y="42" width="42" height="28" rx="4"/>
    <rect class="fig-box" x="216" y="42" width="42" height="28" rx="4"/>
    <path d="M 45 40 Q 69 26 91 40" fill="none" stroke="var(--sl-color-blue)" stroke-width="1.3" marker-start="url(#wz-w5-arr-9)" marker-end="url(#wz-w5-arr-9)"/>
    <path d="M 141 40 Q 165 26 187 40" fill="none" stroke="var(--sl-color-orange)" stroke-width="1.3" marker-start="url(#wz-w5-arr-9)" marker-end="url(#wz-w5-arr-9)"/>
    <rect class="fig-box-blue" x="366" y="42" width="44" height="28" rx="4"/>
    <rect class="fig-box" x="416" y="42" width="44" height="28" rx="4"/>
    <rect class="fig-box" x="466" y="42" width="44" height="28" rx="4"/>
    <rect class="fig-box-blue" x="516" y="42" width="44" height="28" rx="4"/>
    <rect class="fig-box" x="566" y="42" width="44" height="28" rx="4"/>
    <rect class="fig-box" x="616" y="42" width="44" height="28" rx="4"/>
    <path d="M 388 72 L 388 82 L 538 82 L 538 72" fill="none" stroke="var(--sl-color-blue)" stroke-width="1.3"/>
    <g font-size="12" text-anchor="middle">
      <text class="fig-blue" x="45" y="60">5</text><text class="fig-blue" x="93" y="60">3</text>
      <text class="fig-orange" x="141" y="60">8</text><text class="fig-orange" x="189" y="60">4</text><text class="fig-label" x="237" y="60">9</text>
      <text class="fig-blue" x="388" y="60">49</text><text class="fig-label" x="438" y="60">38</text>
      <text class="fig-label" x="488" y="60">65</text><text class="fig-blue" x="538" y="60">13</text>
      <text class="fig-label" x="588" y="60">76</text><text class="fig-label" x="638" y="60">27</text>
    </g>
    <text class="fig-blue" x="69" y="96" text-anchor="middle" font-size="11">5 &gt; 3 交换</text>
    <text class="fig-orange" x="165" y="96" text-anchor="middle" font-size="11">8 &gt; 4 交换</text>
    <text class="fig-muted" x="514" y="102" text-anchor="middle" font-size="11">间隔 d = 3 成组（如 r[1]=49, r[4]=13）组内插排</text>
    <text class="fig-title" x="24" y="148" font-size="12.5">快速：选枢轴 49 双指针划分</text>
    <text class="fig-title" x="366" y="148" font-size="12.5">基数：按个位分配入桶</text>
    <rect class="fig-box-accent" x="24" y="162" width="42" height="28" rx="4"/>
    <rect class="fig-box" x="72" y="162" width="42" height="28" rx="4"/>
    <rect class="fig-box" x="120" y="162" width="42" height="28" rx="4"/>
    <rect class="fig-box" x="168" y="162" width="42" height="28" rx="4"/>
    <rect class="fig-box-blue" x="216" y="162" width="42" height="28" rx="4"/>
    <line class="fig-line-accent" x1="36" y1="202" x2="76" y2="202" marker-end="url(#wz-w5-arr-9)"/>
    <line x1="246" y1="202" x2="206" y2="202" stroke="var(--sl-color-blue)" stroke-width="1.5" fill="none" marker-end="url(#wz-w5-arr-9)"/>
    <rect class="fig-box" x="366" y="162" width="90" height="54" rx="5"/>
    <rect class="fig-box" x="468" y="162" width="90" height="54" rx="5"/>
    <rect class="fig-box" x="570" y="162" width="90" height="54" rx="5"/>
    <g font-size="12" text-anchor="middle">
      <text class="fig-accent" x="45" y="180">49</text><text class="fig-label" x="93" y="180">38</text>
      <text class="fig-label" x="141" y="180">65</text><text class="fig-label" x="189" y="180">97</text><text class="fig-blue" x="237" y="180">13</text>
      <text class="fig-accent" x="45" y="216" font-size="10.5">low</text><text class="fig-blue" x="237" y="216" font-size="10.5">high</text>
      <text class="fig-muted" x="411" y="182" font-size="11">桶 0</text><text class="fig-muted" x="513" y="182" font-size="11">桶 1</text><text class="fig-muted" x="615" y="182" font-size="11">桶 2</text>
      <text class="fig-blue" x="411" y="204">10, 20</text><text class="fig-blue" x="513" y="204">11, 21</text><text class="fig-blue" x="615" y="204">12</text>
    </g>
    <text class="fig-muted" x="175" y="240" text-anchor="middle" font-size="11">一趟后枢轴落位：左 &lt; 49，右 ≥ 49</text>
    <text class="fig-muted" x="514" y="240" text-anchor="middle" font-size="11">不比较大小，按个位/十位依次分配与收集</text>
  </svg>
  <figcaption>常见排序方法操作机制概览：相邻交换、缩小增量分组、双指针划分与按位分桶</figcaption>
</figure>

### 排序的稳定性

若序列中存在**关键字相等**的记录，排序后它们的**相对次序保持不变**，则该排序方法**稳定**；相对次序改变则**不稳定**。

以带两个 49 的序列为例：

- **直接插入排序**：结果中前面的 49 仍在后面的 $49'$ 之前，相对位置未变 → **稳定**。
- **简单选择排序**：一趟交换把后面的 $49'$ 换到了前面 → 相对位置改变 → **不稳定**。

**稳定性的意义**：只对**结构型记录**（一条记录含多个数据项）有意义。若记录只有一个关键字，交换不交换都无所谓。

典型场景：先把学生按数学成绩从高到低排，再按总分从高到低排。若第二次排序是**稳定**的，则总分相同的那些学生中，数学成绩高的仍排在前面——第一次排序的结果被“保留”下来了。这就是多关键字排序的实现方式：按关键字优先级**从次到主**依次做稳定排序。

> **★考点**：稳定性**不是**衡量排序算法优劣的指标，只是选择算法时的一项需求。

> **注意**：证明不稳定只需举出一个反例；证明稳定才需要论证。

### 直接插入排序

**基本思想**（抓牌）：每步把一个待排序记录，按关键字大小插入到前面**已经有序**的子序列中的合适位置，插完仍有序，有序区长度加一；重复到全部插完。

初始时把第一个记录看成**长度为 1 的有序序列**，从第 2 个记录开始逐个插入。插入位置可能在最前、中间或最后（比有序区所有元素都大时原地不动）。

按**找插入位置的方法**不同，插入排序分三种：

| 找位置的方法 | 算法 |
| --- | --- |
| 顺序查找（从后往前） | **直接插入排序** |
| 折半查找 | **折半插入排序** |
| 缩小增量、多趟插入 | **希尔排序** |

直接插入的做法：`r[i]` 先存入 `r[0]` 作**哨兵**，从 `j = i-1` 起向前比较；`r[j].key > r[0].key` 就后移一位，直到 `r[j].key <= r[0].key`，把 `r[0]` 放到 `r[j+1]`。

<figure class="cpd-figure not-content" id="wz-w5-fig-10">
  <svg viewBox="0 0 700 264" role="img" aria-labelledby="wz-w5-title-10">
    <title id="wz-w5-title-10">直接插入排序过程（r[0] 哨兵与后移腾位）</title>
    <defs>
      <marker id="wz-w5-arr-10" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <text class="fig-title" x="30" y="22" font-size="12.5">插入前：i = 7，① 将待插元素 r[7] = 25 存入哨兵单元 r[0]</text>
    <text class="fig-blue" x="304" y="42" text-anchor="middle" font-size="11.5">已排好有序区 r[1..6]</text>
    <text class="fig-muted" x="576" y="42" text-anchor="middle" font-size="11.5">无序区</text>
    <path d="M 516 50 Q 290 22 68 48" fill="none" stroke="var(--sl-color-accent)" stroke-width="1.4" stroke-dasharray="4 3" marker-end="url(#wz-w5-arr-10)"/>
    <rect class="fig-box-accent" x="32" y="52" width="60" height="34" rx="4"/>
    <g class="fig-box-blue">
      <rect x="116" y="52" width="60" height="34"/><rect x="176" y="52" width="60" height="34"/>
      <rect x="236" y="52" width="60" height="34"/><rect x="296" y="52" width="60" height="34"/>
      <rect x="356" y="52" width="60" height="34"/><rect x="416" y="52" width="60" height="34"/>
    </g>
    <rect class="fig-box-orange" x="486" y="52" width="60" height="34"/>
    <rect class="fig-box" x="546" y="52" width="60" height="34"/>
    <g font-size="12.5" text-anchor="middle">
      <text class="fig-accent" x="62" y="74">25</text>
      <text class="fig-blue" x="146" y="74">13</text><text class="fig-blue" x="206" y="74">27</text><text class="fig-blue" x="266" y="74">38</text>
      <text class="fig-blue" x="326" y="74">49</text><text class="fig-blue" x="386" y="74">65</text><text class="fig-blue" x="446" y="74">76</text>
      <text class="fig-orange" x="516" y="74">25</text><text class="fig-label" x="576" y="74">97</text>
    </g>
    <g class="fig-muted" font-size="10.5" text-anchor="middle">
      <text class="fig-accent" x="62" y="102">0(哨兵)</text><text x="146" y="102">1</text><text x="206" y="102">2</text>
      <text x="266" y="102">3</text><text x="326" y="102">4</text><text x="386" y="102">5</text>
      <text x="446" y="102">6</text><text x="516" y="102">7</text><text x="576" y="102">8</text>
    </g>
    <g stroke="var(--sl-color-orange)" stroke-width="1.3" fill="none" marker-end="url(#wz-w5-arr-10)">
      <path d="M 446 112 Q 481 128 512 114"/>
      <path d="M 386 112 Q 416 128 442 114"/>
      <path d="M 326 112 Q 356 128 382 114"/>
      <path d="M 266 112 Q 296 128 322 114"/>
      <path d="M 206 112 Q 236 128 262 114"/>
    </g>
    <text class="fig-orange" x="358" y="138" text-anchor="middle" font-size="10.5">② 从 j = 6 往前比：76, 65, 49, 38, 27 均 &gt; 25，依次后移一格</text>
    <text class="fig-title" x="30" y="160" font-size="12.5">插入后：比到 r[1] = 13 ≤ 25 停下，③ 将哨兵 r[0] = 25 落入 r[2]</text>
    <path d="M 62 208 Q 134 228 202 208" fill="none" stroke="var(--sl-color-green)" stroke-width="1.5" marker-end="url(#wz-w5-arr-10)"/>
    <rect class="fig-box-accent" x="32" y="170" width="60" height="34" rx="4"/>
    <rect class="fig-box-blue" x="116" y="170" width="60" height="34"/>
    <rect class="fig-box-green" x="176" y="170" width="60" height="34"/>
    <rect class="fig-box-blue" x="236" y="170" width="60" height="34"/>
    <rect class="fig-box-blue" x="296" y="170" width="60" height="34"/>
    <rect class="fig-box-blue" x="356" y="170" width="60" height="34"/>
    <rect class="fig-box-blue" x="416" y="170" width="60" height="34"/>
    <rect class="fig-box-blue" x="486" y="170" width="60" height="34"/>
    <rect class="fig-box" x="546" y="170" width="60" height="34"/>
    <g font-size="12.5" text-anchor="middle">
      <text class="fig-accent" x="62" y="192">25</text>
      <text class="fig-blue" x="146" y="192">13</text><text class="fig-green" x="206" y="192">25</text><text class="fig-blue" x="266" y="192">27</text>
      <text class="fig-blue" x="326" y="192">38</text><text class="fig-blue" x="386" y="192">49</text><text class="fig-blue" x="446" y="192">65</text>
      <text class="fig-blue" x="516" y="192">76</text><text class="fig-label" x="576" y="192">97</text>
    </g>
    <g class="fig-muted" font-size="10.5" text-anchor="middle">
      <text class="fig-accent" x="62" y="220">0(哨兵)</text><text x="146" y="220">1</text><text class="fig-green" x="206" y="220">2</text>
      <text x="266" y="220">3</text><text x="326" y="220">4</text><text x="386" y="220">5</text>
      <text x="446" y="220">6</text><text x="516" y="220">7</text><text x="576" y="220">8</text>
    </g>
    <text class="fig-muted" x="350" y="248" text-anchor="middle" font-size="11.5">r[0] 兼作暂存与防越界哨兵；严格小于才后移，相等时停在后面（稳定）</text>
  </svg>
  <figcaption>直接插入排序（带哨兵版）：① 存哨兵 → ② 边比边后移 → ③ 落入 r[j + 1]</figcaption>
</figure>

```c
void InsertSort(SqList &L) {
    for (int i = 2; i <= L.length; i++) {
        if (L.r[i].key < L.r[i-1].key) {      /* 已就位则跳过：正序时只做 n-1 次比较 */
            L.r[0] = L.r[i];                  /* 哨兵：兼作暂存、兼作越界哨兵 */
            int j = i - 1;
            while (L.r[0].key < L.r[j].key) { /* 严格小于：相等即停，故稳定 */
                L.r[j+1] = L.r[j];
                j--;
            }
            L.r[j+1] = L.r[0];
        }
    }
}
```

哨兵的作用：`j` 减到 0 时 `r[0].key < r[0].key` 必假，循环自动终止，循环内**只需一次比较**，不必每轮再判 `j >= 1`。

**性能分析**（基本操作 = 比较 + 移动）：

| 情况 | 比较次数 | 移动次数 | 时间 |
| --- | --- | --- | --- |
| 最好（初始正序） | $n-1$ | $0$ | $O(n)$ |
| 最坏（初始逆序） | $\sum_{i=2}^{n}(i-1)=\dfrac{n(n-1)}{2}$ | 与比较同阶（每次比较后移一格，另加存入/取出哨兵各一次） | $O(n^2)$ |
| 平均 | 约为最坏的一半 | 约为最坏的一半 | $O(n^2)$ |

- 辅助空间只有 `r[0]` 一个单元：$O(1)$，**原地排序**。
- **稳定**：循环条件取严格小于，遇到相等元素就停止，后出现的记录一定排在相等记录之后。
- **自然排序**：原始数据越接近有序，比较和移动越少，速度越快。

> **★考点**：直接插入排序在基本有序时最优，是 $O(n^2)$ 一类里最快的之一；要提高速度只有两条路——减少比较次数、减少移动次数。

### 折半插入排序

有序区既然已经有序，找插入位置就不必从后往前逐个比较，可以直接用**折半查找**，这种插入排序称为**折半插入排序**。

在 `r[1..i-1]` 中查找 `r[i]` 的位置：`low = 1`，`high = i-1`，`mid = ⌊(low+high)/2⌋`；`r[0].key < r[mid].key` 说明应插在左半区，`high = mid-1`；否则 `low = mid+1`。循环结束时 `low > high`，**插入位置就是 `high+1`**。

```c
void BInsertSort(SqList &L) {
    for (int i = 2; i <= L.length; i++) {
        L.r[0] = L.r[i];                 /* 先暂存，后面要腾位置 */
        int low = 1, high = i - 1;
        while (low <= high) {
            int mid = (low + high) / 2;
            if (L.r[0].key < L.r[mid].key) high = mid - 1;
            else low = mid + 1;
        }
        for (int j = i - 1; j >= high + 1; j--)  /* 从 i-1 到 high+1 依次后移一格 */
            L.r[j+1] = L.r[j];
        L.r[high+1] = L.r[0];
    }
}
```

**性能分析**：

- 比较次数降到 $O(n\log n)$，且**与初始状态无关**——正序、逆序、乱序都要走同样多趟折半。
- **移动次数与直接插入完全相同**，取决于初始序列是否基本有序，最坏仍为 $O(n^2)$ 量级。因此总时间复杂度仍是 $O(n^2)$。
- 平均性能**优于直接插入**；但当序列基本有序时，直接插入只需一次比较就能判定“原地不动”，反而比折半插入比较次数少。
- 空间 $O(1)$；**稳定**（`r[0].key < r[mid].key` 取严格小于，相等时插在后面）。

> **注意**：折半插入只**减少比较**，不减少移动；这是它没能改变 $O(n^2)$ 数量级的原因。

<figure class="cpd-figure not-content" id="wz-w5-fig-11">
  <svg viewBox="0 0 700 264" role="img" aria-labelledby="wz-w5-title-11">
    <title id="wz-w5-title-11">折半插入排序二分定位过程（i = 7，r[0] = 25）</title>
    <defs>
      <marker id="wz-w5-arr-11" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <text class="fig-title" x="24" y="22" font-size="12.5">待插 r[0] = 25，在有序区 r[1..6] = [13, 27, 38, 49, 65, 76] 中用折半查找定位</text>
    <g class="fig-muted" font-size="10.5" text-anchor="middle">
      <text x="150" y="42">1</text><text x="210" y="42">2</text><text x="270" y="42">3</text>
      <text x="330" y="42">4</text><text x="390" y="42">5</text><text x="450" y="42">6</text>
    </g>
    <text class="fig-muted" x="24" y="68" font-size="11.5">第 1 轮</text>
    <rect class="fig-box-blue" x="120" y="48" width="60" height="28"/>
    <rect class="fig-box-blue" x="180" y="48" width="60" height="28"/>
    <rect class="fig-box-accent" x="240" y="48" width="60" height="28"/>
    <rect class="fig-box-blue" x="300" y="48" width="60" height="28"/>
    <rect class="fig-box-blue" x="360" y="48" width="60" height="28"/>
    <rect class="fig-box-blue" x="420" y="48" width="60" height="28"/>
    <g font-size="12" text-anchor="middle">
      <text class="fig-blue" x="150" y="66">13</text><text class="fig-blue" x="210" y="66">27</text><text class="fig-accent" x="270" y="66">38 (mid)</text>
      <text class="fig-blue" x="330" y="66">49</text><text class="fig-blue" x="390" y="66">65</text><text class="fig-blue" x="450" y="66">76</text>
    </g>
    <text class="fig-accent" x="490" y="66" font-size="11">25 &lt; 38 → high = 3 − 1 = 2</text>
    <text class="fig-muted" x="24" y="108" font-size="11.5">第 2 轮</text>
    <rect class="fig-box-accent" x="120" y="88" width="60" height="28"/>
    <rect class="fig-box-blue" x="180" y="88" width="60" height="28"/>
    <rect class="fig-box" x="240" y="88" width="60" height="28"/>
    <rect class="fig-box" x="300" y="88" width="60" height="28"/>
    <rect class="fig-box" x="360" y="88" width="60" height="28"/>
    <rect class="fig-box" x="420" y="88" width="60" height="28"/>
    <g font-size="12" text-anchor="middle">
      <text class="fig-accent" x="150" y="106">13 (mid)</text><text class="fig-blue" x="210" y="106">27</text>
      <text class="fig-muted" x="270" y="106">38</text><text class="fig-muted" x="330" y="106">49</text>
      <text class="fig-muted" x="390" y="106">65</text><text class="fig-muted" x="450" y="106">76</text>
    </g>
    <text class="fig-blue" x="490" y="106" font-size="11">25 ≥ 13 → low = 1 + 1 = 2</text>
    <text class="fig-muted" x="24" y="148" font-size="11.5">第 3 轮</text>
    <rect class="fig-box" x="120" y="128" width="60" height="28"/>
    <rect class="fig-box-accent" x="180" y="128" width="60" height="28"/>
    <rect class="fig-box" x="240" y="128" width="60" height="28"/>
    <rect class="fig-box" x="300" y="128" width="60" height="28"/>
    <rect class="fig-box" x="360" y="128" width="60" height="28"/>
    <rect class="fig-box" x="420" y="128" width="60" height="28"/>
    <g font-size="12" text-anchor="middle">
      <text class="fig-muted" x="150" y="146">13</text><text class="fig-accent" x="210" y="146">27 (mid)</text>
      <text class="fig-muted" x="270" y="146">38</text><text class="fig-muted" x="330" y="146">49</text>
      <text class="fig-muted" x="390" y="146">65</text><text class="fig-muted" x="450" y="146">76</text>
    </g>
    <text class="fig-orange" x="490" y="139" font-size="11">25 &lt; 27 → high = 1</text>
    <text class="fig-orange" x="490" y="153" font-size="10.5">low &gt; high，查找停止</text>
    <text class="fig-green" x="24" y="198" font-size="11.5">插入后</text>
    <rect class="fig-box-blue" x="120" y="178" width="60" height="30"/>
    <rect class="fig-box-green" x="180" y="178" width="60" height="30"/>
    <rect class="fig-box-blue" x="240" y="178" width="60" height="30"/>
    <rect class="fig-box-blue" x="300" y="178" width="60" height="30"/>
    <rect class="fig-box-blue" x="360" y="178" width="60" height="30"/>
    <rect class="fig-box-blue" x="420" y="178" width="60" height="30"/>
    <rect class="fig-box-blue" x="480" y="178" width="60" height="30"/>
    <g font-size="12" text-anchor="middle">
      <text class="fig-blue" x="150" y="197">13</text><text class="fig-green" x="210" y="197">25</text>
      <text class="fig-blue" x="270" y="197">27</text><text class="fig-blue" x="330" y="197">38</text>
      <text class="fig-blue" x="390" y="197">49</text><text class="fig-blue" x="450" y="197">65</text>
      <text class="fig-blue" x="510" y="197">76</text>
    </g>
    <text class="fig-green" x="550" y="197" font-size="11">插位 = high + 1 = 2</text>
    <rect class="fig-box-subtle" x="24" y="222" width="652" height="30" rx="5"/>
    <text class="fig-muted" x="350" y="241" text-anchor="middle" font-size="11.5">比较仅 3 次（降至 O(n log n)），但 r[2..6] 仍要逐格后移 5 次 → 不减少移动，总时间仍为 O(n²)</text>
  </svg>
  <figcaption>折半插入排序过程拆解：二分定位插入点 high + 1，减少比较次数但移动次数与直接插入相同</figcaption>
</figure>

### 希尔排序

**出发点**：直接插入排序在两处最快——记录数少、序列基本有序。能否把待排序列**分成若干子序列**（每组的元素少），先做插入排序让数据“大体有序”，最后再对整个序列做一次直接插入？同时，分组后一次比较可以**跨越大步**移动，让元素快速接近最终位置。

**做法**：取一个递减的**增量序列** $d_1>d_2>\dots>d_t=1$，按增量 $d_k$ 把相隔 $d_k$ 的记录分成一组，组内做直接插入排序；增量逐趟缩小，最后一趟 $d_k=1$ 就是全体直接插入排序。

以 11 个记录、增量 5 → 3 → 1 为例：

- $d=5$：第 1、6、11 个记录为一组，第 2、7 个为一组……组内插入排序。大关键字一次跳很远往后，小关键字一次跳到前面，序列**大大趋于有序**。
- $d=3$：按间隔 3 重新分组，再各自插入排序，更加有序。
- $d=1$：此时序列已基本有序，最后一遍直接插入只需很少的移动。

**增量序列的要求**：

- 必须**递减**，且**最后一个必须为 1**（否则不能保证整体有序）。
- 各增量之间除 1 外**不能有公因子**（互质），这样各趟分组不会总是落在同一批元素上。
- 最佳增量序列至今没有定论。

```c
void ShellSort(SqList &L, int dl[], int t) {   /* dl[0..t-1] 为递减增量序列，dl[t-1] 必须为 1 */
    for (int k = 0; k < t; k++) {
        int dk = dl[k];
        for (int i = dk + 1; i <= L.length; i++) {
            if (L.r[i].key < L.r[i-dk].key) {
                L.r[0] = L.r[i];
                int j;
                for (j = i - dk; j > 0 && L.r[0].key < L.r[j].key; j -= dk)
                    L.r[j+dk] = L.r[j];        /* 每次跨 dk 位，而不是 1 位 */
                L.r[j+dk] = L.r[0];
            }
        }
    }
}
```

与直接插入的唯一区别：所有“减 1”的位置运算都换成“减 `dk`”——找下一个元素是 `j-dk`，后移也是移到 `j+dk`。

**性能**：效率取决于增量序列。

- 最好（初始正序）$O(n)$；最坏 $O(n^2)$；平均约 $O(n^{1.3})$，经验公式给出 $n^{1.25}\sim1.6n^{1.25}$。希尔排序的精确复杂度是数学上尚未解决的问题，只能估计。
- 空间 $O(1)$。
- **不稳定**：取增量 2 分组，两个相等关键字可能被分到不同组，排完后相对次序颠倒，举出这一个反例即可证明。
- **不适合链式存储**：按间隔 $d_k$ 找第几个元素必须逐个计数，链式结构上开销反而大于顺序表。

> **注意**：希尔排序的一趟只保证**每个子序列内部**有序，不能保证任何元素到达最终位置；全部 $t$ 趟结束（最后一趟 $d=1$）才整体有序。

<figure class="cpd-figure not-content" id="wz-w5-fig-12">
  <svg viewBox="0 0 700 264" role="img" aria-labelledby="wz-w5-title-12">
    <title id="wz-w5-title-12">希尔排序缩小增量过程（d = 5 → d = 3 → d = 1）</title>
    <text class="fig-title" x="24" y="22" font-size="12.5">初始序列：[49, 38, 65, 97, 76, 13, 27, 49', 55, 04]（同色方块属于同一增量组）</text>
    <text class="fig-blue" x="24" y="60" font-size="11.5">d = 5 分组</text>
    <g font-size="12" text-anchor="middle">
      <rect class="fig-box-blue" x="108" y="42" width="48" height="26" rx="4"/><text class="fig-blue" x="132" y="59">49</text>
      <rect class="fig-box-orange" x="162" y="42" width="48" height="26" rx="4"/><text class="fig-orange" x="186" y="59">38</text>
      <rect class="fig-box-green" x="216" y="42" width="48" height="26" rx="4"/><text class="fig-green" x="240" y="59">65</text>
      <rect class="fig-box-purple" x="270" y="42" width="48" height="26" rx="4"/><text class="fig-purple" x="294" y="59">97</text>
      <rect class="fig-box-accent" x="324" y="42" width="48" height="26" rx="4"/><text class="fig-accent" x="348" y="59">76</text>
      <rect class="fig-box-blue" x="378" y="42" width="48" height="26" rx="4"/><text class="fig-blue" x="402" y="59">13</text>
      <rect class="fig-box-orange" x="432" y="42" width="48" height="26" rx="4"/><text class="fig-orange" x="456" y="59">27</text>
      <rect class="fig-box-green" x="486" y="42" width="48" height="26" rx="4"/><text class="fig-green" x="510" y="59">49'</text>
      <rect class="fig-box-purple" x="540" y="42" width="48" height="26" rx="4"/><text class="fig-purple" x="564" y="59">55</text>
      <rect class="fig-box-accent" x="594" y="42" width="48" height="26" rx="4"/><text class="fig-accent" x="618" y="59">04</text>
    </g>
    <path d="M 132 40 L 132 33 L 402 33 L 402 40" fill="none" stroke="var(--sl-color-blue)" stroke-width="1.2"/>
    <path d="M 240 70 L 240 76 L 510 76 L 510 70" fill="none" stroke="var(--sl-color-green)" stroke-width="1.2"/>
    <text class="fig-muted" x="24" y="106" font-size="11.5">d = 5 排后</text>
    <g font-size="12" text-anchor="middle">
      <rect class="fig-box-blue" x="108" y="88" width="48" height="26" rx="4"/><text class="fig-blue" x="132" y="105">13</text>
      <rect class="fig-box-orange" x="162" y="88" width="48" height="26" rx="4"/><text class="fig-orange" x="186" y="105">27</text>
      <rect class="fig-box-green" x="216" y="88" width="48" height="26" rx="4"/><text class="fig-green" x="240" y="105">49'</text>
      <rect class="fig-box-purple" x="270" y="88" width="48" height="26" rx="4"/><text class="fig-purple" x="294" y="105">55</text>
      <rect class="fig-box-accent" x="324" y="88" width="48" height="26" rx="4"/><text class="fig-accent" x="348" y="105">04</text>
      <rect class="fig-box-blue" x="378" y="88" width="48" height="26" rx="4"/><text class="fig-blue" x="402" y="105">49</text>
      <rect class="fig-box-orange" x="432" y="88" width="48" height="26" rx="4"/><text class="fig-orange" x="456" y="105">38</text>
      <rect class="fig-box-green" x="486" y="88" width="48" height="26" rx="4"/><text class="fig-green" x="510" y="105">65</text>
      <rect class="fig-box-purple" x="540" y="88" width="48" height="26" rx="4"/><text class="fig-purple" x="564" y="105">97</text>
      <rect class="fig-box-accent" x="594" y="88" width="48" height="26" rx="4"/><text class="fig-accent" x="618" y="105">76</text>
    </g>
    <text class="fig-muted" x="24" y="152" font-size="11.5">d = 3 排后</text>
    <g font-size="12" text-anchor="middle">
      <rect class="fig-box-blue" x="108" y="134" width="48" height="26" rx="4"/><text class="fig-blue" x="132" y="151">13</text>
      <rect class="fig-box-orange" x="162" y="134" width="48" height="26" rx="4"/><text class="fig-orange" x="186" y="151">04</text>
      <rect class="fig-box-purple" x="216" y="134" width="48" height="26" rx="4"/><text class="fig-purple" x="240" y="151">49'</text>
      <rect class="fig-box-blue" x="270" y="134" width="48" height="26" rx="4"/><text class="fig-blue" x="294" y="151">38</text>
      <rect class="fig-box-orange" x="324" y="134" width="48" height="26" rx="4"/><text class="fig-orange" x="348" y="151">27</text>
      <rect class="fig-box-purple" x="378" y="134" width="48" height="26" rx="4"/><text class="fig-purple" x="402" y="151">49</text>
      <rect class="fig-box-blue" x="432" y="134" width="48" height="26" rx="4"/><text class="fig-blue" x="456" y="151">55</text>
      <rect class="fig-box-orange" x="486" y="134" width="48" height="26" rx="4"/><text class="fig-orange" x="510" y="151">65</text>
      <rect class="fig-box-purple" x="540" y="134" width="48" height="26" rx="4"/><text class="fig-purple" x="564" y="151">97</text>
      <rect class="fig-box-blue" x="594" y="134" width="48" height="26" rx="4"/><text class="fig-blue" x="618" y="151">76</text>
    </g>
    <text class="fig-green" x="24" y="198" font-size="11.5">d = 1 全排</text>
    <g font-size="12" text-anchor="middle">
      <rect class="fig-box-green" x="108" y="180" width="48" height="26" rx="4"/><text class="fig-green" x="132" y="197">04</text>
      <rect class="fig-box-green" x="162" y="180" width="48" height="26" rx="4"/><text class="fig-green" x="186" y="197">13</text>
      <rect class="fig-box-green" x="216" y="180" width="48" height="26" rx="4"/><text class="fig-green" x="240" y="197">27</text>
      <rect class="fig-box-green" x="270" y="180" width="48" height="26" rx="4"/><text class="fig-green" x="294" y="197">38</text>
      <rect class="fig-box-red" x="324" y="180" width="48" height="26" rx="4"/><text class="fig-red" x="348" y="197">49'</text>
      <rect class="fig-box-red" x="378" y="180" width="48" height="26" rx="4"/><text class="fig-red" x="402" y="197">49</text>
      <rect class="fig-box-green" x="432" y="180" width="48" height="26" rx="4"/><text class="fig-green" x="456" y="197">55</text>
      <rect class="fig-box-green" x="486" y="180" width="48" height="26" rx="4"/><text class="fig-green" x="510" y="197">65</text>
      <rect class="fig-box-green" x="540" y="180" width="48" height="26" rx="4"/><text class="fig-green" x="564" y="197">76</text>
      <rect class="fig-box-green" x="594" y="180" width="48" height="26" rx="4"/><text class="fig-green" x="618" y="197">97</text>
    </g>
    <rect class="fig-box-subtle" x="24" y="218" width="652" height="32" rx="5"/>
    <text class="fig-muted" x="350" y="238" text-anchor="middle" font-size="11.5">小元素（04, 13, 27）借大增量一次跨越到前端；不同组独立排序导致 49' 跳到 49 前 → 不稳定</text>
  </svg>
  <figcaption>希尔排序缩小增量分组追踪：d = 5（5 组）→ d = 3（3 组）→ d = 1（全体直接插排）</figcaption>
</figure>

> **交互演示**：[直接插入 / 折半插入 / 希尔排序](/lab/chapter-10/#lab-insertion)

### 冒泡排序

**交换排序**的基本思想：比较两个记录，若二者**逆序**（与最终要求相反，升序时即前大后小）就交换，直到全部有序。冒泡排序是最基本的交换排序。

**过程**：每趟从表头开始，依次比较**相邻**的两个记录 `r[j]` 与 `r[j+1]`，逆序则交换。一趟下来，当前无序区中最大的记录被“推”到区间末尾——像气泡一样，重的下沉、轻的上浮，故名冒泡（起泡）排序。

- $n$ 个记录共需 $n-1$ 趟；第 $m$ 趟比较 $n-m$ 次（第 1 趟比较 $n-1$ 次，最后一趟只剩两个元素比 1 次）。
- 每趟结束**确定一个最大值的最终位置**，同时前面的元素也被部分理顺，所以实际表现比其它 $O(n^2)$ 算法好。

```c
void BubbleSort(SqList &L) {
    for (int m = 1; m <= L.length - 1; m++) {
        int flag = 0;                          /* 本趟是否发生交换 */
        for (int j = 1; j <= L.length - m; j++) {
            if (L.r[j].key > L.r[j+1].key) {
                swap(L.r[j], L.r[j+1]);
                flag = 1;
            }
        }
        if (flag == 0) break;                  /* 整趟无交换：已经有序，提前结束 */
    }
}
```

**改进（flag 标志）**：若某一趟从头到尾没有发生交换，说明序列已经有序，后面各趟全部可以省略。加了 flag 后，正序输入只跑一趟就结束。

**性能分析**：

| 情况 | 比较次数 | 移动次数 | 时间 |
| --- | --- | --- | --- |
| 最好（正序 + flag） | $n-1$ | $0$ | $O(n)$ |
| 最坏（逆序） | $\dfrac{n(n-1)}{2}$ | $3\cdot\dfrac{n(n-1)}{2}$（每次交换 3 次赋值） | $O(n^2)$ |
| 平均 | $O(n^2)$ | $O(n^2)$ | $O(n^2)$ |

- 空间：交换用 1 个临时单元，$O(1)$，原地排序。
- **稳定**：只有严格逆序（`>`）才交换，相等元素不换位。
- **自然排序**：基本有序时接近 $O(n)$。

<figure class="cpd-figure not-content" id="wz-w5-fig-13">
  <svg viewBox="0 0 700 252" role="img" aria-labelledby="wz-w5-title-13">
    <title id="wz-w5-title-13">冒泡排序（含 flag 提前终止）逐趟演进过程</title>
    <defs>
      <marker id="wz-w5-arr-13" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <text class="fig-title" x="24" y="22" font-size="12.5">冒泡排序逐趟演示（[49, 38, 65, 97, 76, 13, 27]）：每趟相邻逆序交换，最大值沉底就位</text>
    <g font-size="11.5">
      <text class="fig-muted" x="24" y="56">初始序列</text>
      <text class="fig-blue" x="24" y="96">第 1 趟后</text>
      <text class="fig-blue" x="24" y="136">第 2 趟后</text>
      <text class="fig-blue" x="24" y="176">第 5 趟后</text>
      <text class="fig-green" x="24" y="216">第 6 趟检</text>
    </g>
    <g font-size="12" text-anchor="middle">
      <rect class="fig-box" x="104" y="38" width="44" height="26" rx="4"/><text class="fig-label" x="126" y="55">49</text>
      <rect class="fig-box" x="154" y="38" width="44" height="26" rx="4"/><text class="fig-label" x="176" y="55">38</text>
      <rect class="fig-box" x="204" y="38" width="44" height="26" rx="4"/><text class="fig-label" x="226" y="55">65</text>
      <rect class="fig-box-accent" x="254" y="38" width="44" height="26" rx="4"/><text class="fig-accent" x="276" y="55">97</text>
      <rect class="fig-box" x="304" y="38" width="44" height="26" rx="4"/><text class="fig-label" x="326" y="55">76</text>
      <rect class="fig-box" x="354" y="38" width="44" height="26" rx="4"/><text class="fig-label" x="376" y="55">13</text>
      <rect class="fig-box" x="404" y="38" width="44" height="26" rx="4"/><text class="fig-label" x="426" y="55">27</text>
      <rect class="fig-box" x="104" y="78" width="44" height="26" rx="4"/><text class="fig-label" x="126" y="95">38</text>
      <rect class="fig-box" x="154" y="78" width="44" height="26" rx="4"/><text class="fig-label" x="176" y="95">49</text>
      <rect class="fig-box" x="204" y="78" width="44" height="26" rx="4"/><text class="fig-label" x="226" y="95">65</text>
      <rect class="fig-box-blue" x="254" y="78" width="44" height="26" rx="4"/><text class="fig-blue" x="276" y="95">76</text>
      <rect class="fig-box" x="304" y="78" width="44" height="26" rx="4"/><text class="fig-label" x="326" y="95">13</text>
      <rect class="fig-box" x="354" y="78" width="44" height="26" rx="4"/><text class="fig-label" x="376" y="95">27</text>
      <rect class="fig-box-green" x="404" y="78" width="44" height="26" rx="4"/><text class="fig-green" x="426" y="95">97</text>
      <rect class="fig-box" x="104" y="118" width="44" height="26" rx="4"/><text class="fig-label" x="126" y="135">38</text>
      <rect class="fig-box" x="154" y="118" width="44" height="26" rx="4"/><text class="fig-label" x="176" y="135">49</text>
      <rect class="fig-box" x="204" y="118" width="44" height="26" rx="4"/><text class="fig-label" x="226" y="135">65</text>
      <rect class="fig-box" x="254" y="118" width="44" height="26" rx="4"/><text class="fig-label" x="276" y="135">13</text>
      <rect class="fig-box" x="304" y="118" width="44" height="26" rx="4"/><text class="fig-label" x="326" y="135">27</text>
      <rect class="fig-box-green" x="354" y="118" width="44" height="26" rx="4"/><text class="fig-green" x="376" y="135">76</text>
      <rect class="fig-box-green" x="404" y="118" width="44" height="26" rx="4"/><text class="fig-green" x="426" y="135">97</text>
      <rect class="fig-box-blue" x="104" y="158" width="44" height="26" rx="4"/><text class="fig-blue" x="126" y="175">13</text>
      <rect class="fig-box-green" x="154" y="158" width="44" height="26" rx="4"/><text class="fig-green" x="176" y="175">27</text>
      <rect class="fig-box-green" x="204" y="158" width="44" height="26" rx="4"/><text class="fig-green" x="226" y="175">38</text>
      <rect class="fig-box-green" x="254" y="158" width="44" height="26" rx="4"/><text class="fig-green" x="276" y="175">49</text>
      <rect class="fig-box-green" x="304" y="158" width="44" height="26" rx="4"/><text class="fig-green" x="326" y="175">65</text>
      <rect class="fig-box-green" x="354" y="158" width="44" height="26" rx="4"/><text class="fig-green" x="376" y="175">76</text>
      <rect class="fig-box-green" x="404" y="158" width="44" height="26" rx="4"/><text class="fig-green" x="426" y="175">97</text>
      <rect class="fig-box-green" x="104" y="198" width="44" height="26" rx="4"/><text class="fig-green" x="126" y="215">13</text>
      <rect class="fig-box-green" x="154" y="198" width="44" height="26" rx="4"/><text class="fig-green" x="176" y="215">27</text>
      <rect class="fig-box-green" x="204" y="198" width="44" height="26" rx="4"/><text class="fig-green" x="226" y="215">38</text>
      <rect class="fig-box-green" x="254" y="198" width="44" height="26" rx="4"/><text class="fig-green" x="276" y="215">49</text>
      <rect class="fig-box-green" x="304" y="198" width="44" height="26" rx="4"/><text class="fig-green" x="326" y="215">65</text>
      <rect class="fig-box-green" x="354" y="198" width="44" height="26" rx="4"/><text class="fig-green" x="376" y="215">76</text>
      <rect class="fig-box-green" x="404" y="198" width="44" height="26" rx="4"/><text class="fig-green" x="426" y="215">97</text>
    </g>
    <path d="M 276 66 Q 351 76 422 66" fill="none" stroke="var(--sl-color-accent)" stroke-width="1.3" marker-end="url(#wz-w5-arr-13)"/>
    <g font-size="11">
      <text class="fig-muted" x="466" y="55">最大 97 准备向右冒泡</text>
      <text class="fig-blue" x="466" y="95">比较 6 次，flag = 1，97 落位</text>
      <text class="fig-blue" x="466" y="135">比较 5 次，flag = 1，76 落位</text>
      <text class="fig-muted" x="466" y="175">…第 5 趟后实际已全部有序</text>
      <text class="fig-green" x="466" y="215">全程无交换（flag = 0）→ break</text>
    </g>
    <text class="fig-muted" x="350" y="242" text-anchor="middle" font-size="11">严格大于（&gt;）才交换，相等元素不换位 → 稳定；正序输入仅跑 1 趟（n − 1 次比较）即结束</text>
  </svg>
  <figcaption>冒泡排序追踪：每趟确定 1 个最大值的最终位置，flag = 0 标志可在已完全有序时提前终止</figcaption>
</figure>

### 快速排序

**基本思想**：从待排序列中任取一个元素作**枢轴（pivot，也称中心点、分界点、轴心）**，把所有比它小的元素放到它前面、比它大的放到它后面。一趟划分后，枢轴落到**最终位置**，同时把原表分成左右两个子表；对两个子表递归地重复同样操作，直到子表只剩一个元素（递归出口）。

**划分的高效实现**（只需一个额外单元，双指针交替逼近）：

1. 把枢轴 `r[low]` 存入 `r[0]`，`low` 位置空出。
2. `high` 从后往前找**比枢轴小**的元素，搬到 `r[low]`；`high` 位置空出。
3. `low` 从前往后找**比枢轴大**的元素，搬到 `r[high]`；`low` 位置空出。
4. 重复 2、3，直到 `low == high`，此位置即枢轴的最终位置，把 `r[0]` 放回。

```c
int Partition(SqList &L, int low, int high) {
    KeyType pivot = L.r[low].key;            /* 枢轴值 */
    L.r[0] = L.r[low];                       /* 枢轴暂存到 0 号单元 */
    while (low < high) {
        while (low < high && L.r[high].key >= pivot) high--;  /* 从后找小的 */
        L.r[low] = L.r[high];
        while (low < high && L.r[low].key <= pivot) low++;    /* 从前找大的 */
        L.r[high] = L.r[low];
    }
    L.r[low] = L.r[0];
    return low;                             /* 枢轴最终位置 */
}

void QSort(SqList &L, int low, int high) {
    if (low < high) {
        int pivotpos = Partition(L, low, high);
        QSort(L, low, pivotpos - 1);
        QSort(L, pivotpos + 1, high);
    }
}
```

这种“两头向中间交替搬运”的划分方式只借用 `r[0]` 一个单元；而“另开一个数组、小的从左放、大的从右放”虽然直观，却要多花 $O(n)$ 空间，不可取。

**过程拆解**：对 `[49,38,65,97,76,13,27]` 做一趟划分，枢轴 `pivot=49`（`r[0]`）：

| 步骤 | `low` | `high` | 动作 | 数组状态（空位用 `_`） |
|:---:|:---:|:---:|:---|:---|
| 初始 | 1 | 7 | `r[0]=49`，1 号位空出 | `[49,_,38,65,97,76,13,27]` |
| 1 | 1 | 7 | `high` 找到 27 < 49，搬到 `r[1]` | `[49,27,38,65,97,76,13,_]` |
| 2 | 1 | 7 | `low` 找到 65 > 49，搬到 `r[7]` | `[49,27,38,_,97,76,13,65]` |
| 3 | 2 | 7 | `high` 找到 13 < 49，搬到 `r[2]` | `[49,27,38,13,97,76,_,65]` |
| 4 | 2 | 6 | `low` 找到 97 > 49，搬到 `r[6]` | `[49,27,38,13,_,76,97,65]` |
| 5 | 3 | 5 | `high` 连续跳过 76、97，`high=3`，`low==high` | `[49,27,38,13,_,76,97,65]` |
| 6 | 3 | 3 | 枢轴放回 `r[3]` | `[27,38,13,49,76,97,65]` |

一趟后 49 落到最终位置，左边都小于 49，右边都不小于 49。

<figure class="cpd-figure not-content" id="wz-w5-fig-14">
  <svg viewBox="0 0 700 298" role="img" aria-labelledby="wz-w5-title-14">
    <title id="wz-w5-title-14">快速排序一趟划分 Partition 过程演示（r[0] = 49）</title>
    <text class="fig-title" x="24" y="22" font-size="12.5">Partition(L, 1, 7)：r[0] = 49 暂存，low 与 high 交替挖坑搬运</text>
    <g font-size="11.5">
      <text class="fig-muted" x="24" y="54">初始</text>
      <text class="fig-muted" x="24" y="92">① high↓</text>
      <text class="fig-muted" x="24" y="130">② low↑</text>
      <text class="fig-muted" x="24" y="168">③ high↓</text>
      <text class="fig-muted" x="24" y="206">④ low↑</text>
      <text class="fig-green" x="24" y="244">⑤ 归位</text>
    </g>
    <g font-size="12" text-anchor="middle">
      <rect class="fig-box-orange" x="92" y="34" width="44" height="28" rx="4"/><text class="fig-orange" x="114" y="52">[空]</text>
      <rect class="fig-box" x="140" y="34" width="44" height="28" rx="4"/><text class="fig-label" x="162" y="52">38</text>
      <rect class="fig-box" x="188" y="34" width="44" height="28" rx="4"/><text class="fig-label" x="210" y="52">65</text>
      <rect class="fig-box" x="236" y="34" width="44" height="28" rx="4"/><text class="fig-label" x="258" y="52">97</text>
      <rect class="fig-box" x="284" y="34" width="44" height="28" rx="4"/><text class="fig-label" x="306" y="52">76</text>
      <rect class="fig-box" x="332" y="34" width="44" height="28" rx="4"/><text class="fig-label" x="354" y="52">13</text>
      <rect class="fig-box-blue" x="380" y="34" width="44" height="28" rx="4"/><text class="fig-blue" x="402" y="52">27</text>
      <rect class="fig-box-blue" x="92" y="72" width="44" height="28" rx="4"/><text class="fig-blue" x="114" y="90">27</text>
      <rect class="fig-box" x="140" y="72" width="44" height="28" rx="4"/><text class="fig-label" x="162" y="90">38</text>
      <rect class="fig-box-blue" x="188" y="72" width="44" height="28" rx="4"/><text class="fig-blue" x="210" y="90">65</text>
      <rect class="fig-box" x="236" y="72" width="44" height="28" rx="4"/><text class="fig-label" x="258" y="90">97</text>
      <rect class="fig-box" x="284" y="72" width="44" height="28" rx="4"/><text class="fig-label" x="306" y="90">76</text>
      <rect class="fig-box" x="332" y="72" width="44" height="28" rx="4"/><text class="fig-label" x="354" y="90">13</text>
      <rect class="fig-box-orange" x="380" y="72" width="44" height="28" rx="4"/><text class="fig-orange" x="402" y="90">[空]</text>
      <rect class="fig-box" x="92" y="110" width="44" height="28" rx="4"/><text class="fig-label" x="114" y="128">27</text>
      <rect class="fig-box" x="140" y="110" width="44" height="28" rx="4"/><text class="fig-label" x="162" y="128">38</text>
      <rect class="fig-box-orange" x="188" y="110" width="44" height="28" rx="4"/><text class="fig-orange" x="210" y="128">[空]</text>
      <rect class="fig-box" x="236" y="110" width="44" height="28" rx="4"/><text class="fig-label" x="258" y="128">97</text>
      <rect class="fig-box" x="284" y="110" width="44" height="28" rx="4"/><text class="fig-label" x="306" y="128">76</text>
      <rect class="fig-box-blue" x="332" y="110" width="44" height="28" rx="4"/><text class="fig-blue" x="354" y="128">13</text>
      <rect class="fig-box-blue" x="380" y="110" width="44" height="28" rx="4"/><text class="fig-blue" x="402" y="128">65</text>
      <rect class="fig-box" x="92" y="148" width="44" height="28" rx="4"/><text class="fig-label" x="114" y="166">27</text>
      <rect class="fig-box" x="140" y="148" width="44" height="28" rx="4"/><text class="fig-label" x="162" y="166">38</text>
      <rect class="fig-box-blue" x="188" y="148" width="44" height="28" rx="4"/><text class="fig-blue" x="210" y="166">13</text>
      <rect class="fig-box-blue" x="236" y="148" width="44" height="28" rx="4"/><text class="fig-blue" x="258" y="166">97</text>
      <rect class="fig-box" x="284" y="148" width="44" height="28" rx="4"/><text class="fig-label" x="306" y="166">76</text>
      <rect class="fig-box-orange" x="332" y="148" width="44" height="28" rx="4"/><text class="fig-orange" x="354" y="166">[空]</text>
      <rect class="fig-box" x="380" y="148" width="44" height="28" rx="4"/><text class="fig-label" x="402" y="166">65</text>
      <rect class="fig-box" x="92" y="186" width="44" height="28" rx="4"/><text class="fig-label" x="114" y="204">27</text>
      <rect class="fig-box" x="140" y="186" width="44" height="28" rx="4"/><text class="fig-label" x="162" y="204">38</text>
      <rect class="fig-box" x="188" y="186" width="44" height="28" rx="4"/><text class="fig-label" x="210" y="204">13</text>
      <rect class="fig-box-orange" x="236" y="186" width="44" height="28" rx="4"/><text class="fig-orange" x="258" y="204">[空]</text>
      <rect class="fig-box" x="284" y="186" width="44" height="28" rx="4"/><text class="fig-label" x="306" y="204">76</text>
      <rect class="fig-box-blue" x="332" y="186" width="44" height="28" rx="4"/><text class="fig-blue" x="354" y="204">97</text>
      <rect class="fig-box" x="380" y="186" width="44" height="28" rx="4"/><text class="fig-label" x="402" y="204">65</text>
      <rect class="fig-box-green" x="92" y="224" width="44" height="28" rx="4"/><text class="fig-green" x="114" y="242">27</text>
      <rect class="fig-box-green" x="140" y="224" width="44" height="28" rx="4"/><text class="fig-green" x="162" y="242">38</text>
      <rect class="fig-box-green" x="188" y="224" width="44" height="28" rx="4"/><text class="fig-green" x="210" y="242">13</text>
      <rect class="fig-box-accent" x="236" y="224" width="44" height="28" rx="4"/><text class="fig-accent" x="258" y="242">49</text>
      <rect class="fig-box-purple" x="284" y="224" width="44" height="28" rx="4"/><text class="fig-purple" x="306" y="242">76</text>
      <rect class="fig-box-purple" x="332" y="224" width="44" height="28" rx="4"/><text class="fig-purple" x="354" y="242">97</text>
      <rect class="fig-box-purple" x="380" y="224" width="44" height="28" rx="4"/><text class="fig-purple" x="402" y="242">65</text>
    </g>
    <g font-size="11.5">
      <text class="fig-muted" x="438" y="52">low = 1 留坑，high = 7 指向 27</text>
      <text class="fig-blue" x="438" y="90">27 &lt; 49 填左坑；low 停在 65</text>
      <text class="fig-blue" x="438" y="128">65 &gt; 49 填右坑；high 搬 13</text>
      <text class="fig-blue" x="438" y="166">13 &lt; 49 填左坑；low 停在 97</text>
      <text class="fig-orange" x="438" y="204">97 &gt; 49 填右坑；high 与 low 相遇</text>
      <text class="fig-green" x="438" y="242">low == high = 4，49 落到最终位置</text>
    </g>
    <text class="fig-muted" x="350" y="280" text-anchor="middle" font-size="11.5">一趟划分仅借 r[0] 一个辅助单元，左右子表 [1..3] 与 [5..7] 递归</text>
  </svg>
  <figcaption>快速排序一趟划分追踪：双指针从两端向中间交替填坑</figcaption>
</figure>

**性能分析**：

- 一趟划分需扫视整个区间，$O(n)$；递归深度平均 $O(\log n)$，故平均时间 $O(n\log n)$。
- 它是所有**内部排序中平均速度最快**的一种。
- **最坏情况**：初始序列**正序或逆序**（基本有序也算）。每次划分总是一边为空、另一边含其余全部元素，递归深度退化为 $n$，时间退化为 $O(n^2)$，效果等同冒泡排序。
- 因此快速排序是**非自然排序**：**越乱越好**。序列越随机，划分出的两个子表长度越均衡，速度越快。改善办法是改变枢轴的选法（取中间元素、随机取、三点取中）。
- 空间：递归必须用**系统栈**保存每层现场，平均 $O(\log n)$，最坏 $O(n)$——**不是原地排序**（即使用户自定义栈代替递归，同样要占空间）。
- **不稳定**：划分时的长距离搬运会改变相等元素的相对次序（如枢轴 49 与序列中另一个 49 在归位时前后颠倒）。

> **★考点**：快排“越有序越慢、越乱越快”，与插入、冒泡、希尔完全相反；最坏 $O(n^2)$ 但仍比其它 $O(n^2)$ 算法快。

> **交互演示**：[冒泡排序与快速排序](/lab/chapter-10/#lab-bubble)

### 简单选择排序

**基本思想**：每趟从待排记录中选出**最小**（升序）的记录，与当前区间的第一个记录交换。第 $i$ 趟在 `r[i..n]` 中选最小者与 `r[i]` 交换，$i$ 从 1 到 $n-1$，共 $n-1$ 趟。

找最小值用**打擂台**：假定当前 `r[i]` 最小，用 `k` 记录其下标，依次与后面每个元素比较，遇到更小的就把 `k` 改成它的下标；比较全部结束后，若 `k != i` 则交换。

```c
void SelectSort(SqList &L) {
    for (int i = 1; i < L.length; i++) {
        int k = i;
        for (int j = i + 1; j <= L.length; j++)
            if (L.r[j].key < L.r[k].key) k = j;   /* 打擂台，记录最小者下标 */
        if (k != i) swap(L.r[i], L.r[k]);
    }
}
```

**性能分析**：

- **比较次数与初始状态无关**：第 $i$ 趟比较 $n-i$ 次，总计
$$
\sum_{i=1}^{n-1}(n-i)=\frac{n(n-1)}{2}
$$
  因此最好、最坏、平均时间**都是** $O(n^2)$。
- 移动次数：最好（已有序）为 0；最坏（逆序）为 $3(n-1)$ 次赋值。
- 空间：交换用 1 个临时单元，$O(1)$，原地排序。
- **不稳定**：交换是远距离的，可能把后面的相等元素换到前面来（例如两个相等的 8，靠后的那个被换到了前面）。有的教材写「稳定」，但可以举出反例证明不稳定，**以反例为准**；把“交换”改成“依次后移再插入”即可**稳定化**。

> **注意**：简单选择排序的比较次数恒定，不能靠“初始基本有序”提速；它的优点是**移动次数少**。

<figure class="cpd-figure not-content" id="wz-w5-fig-16">
  <svg viewBox="0 0 700 326" role="img" aria-labelledby="wz-w5-title-16">
    <title id="wz-w5-title-16">简单选择排序打擂台选最值与 [8₁, 8₂, 2] 不稳定反例演示</title>
    <defs>
      <marker id="wz-w5-arr-16" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <text class="fig-title" x="24" y="22" font-size="12.5">简单选择排序：打擂台选最小值与 [8₁, 8₂, 2] 长距离交换破坏稳定性</text>
    <g class="fig-muted" font-size="10.5" text-anchor="middle">
      <text x="138" y="44">1 (i)</text><text x="198" y="44">2</text><text x="258" y="44">3</text><text x="318" y="44">4 (k)</text><text x="378" y="44">5</text>
    </g>
    <text class="fig-blue" x="24" y="68" font-size="11.5">第 1 趟打擂</text>
    <path d="M 138 78 Q 228 106 318 78" fill="none" stroke="var(--sl-color-accent)" stroke-width="1.35" marker-start="url(#wz-w5-arr-16)" marker-end="url(#wz-w5-arr-16)"/>
    <g font-size="12" text-anchor="middle">
      <rect class="fig-box-orange" x="112" y="50" width="52" height="28" rx="4"/><text class="fig-orange" x="138" y="68">49</text>
      <rect class="fig-box" x="172" y="50" width="52" height="28" rx="4"/><text class="fig-label" x="198" y="68">38</text>
      <rect class="fig-box" x="232" y="50" width="52" height="28" rx="4"/><text class="fig-label" x="258" y="68">65</text>
      <rect class="fig-box-accent" x="292" y="50" width="52" height="28" rx="4"/><text class="fig-accent" x="318" y="68">13</text>
      <rect class="fig-box" x="352" y="50" width="52" height="28" rx="4"/><text class="fig-label" x="378" y="68">27</text>
    </g>
    <rect class="fig-box" x="176" y="84" width="104" height="18" rx="4"/>
    <text class="fig-accent" x="228" y="96" text-anchor="middle" font-size="10.5">swap(r[1], r[4])</text>
    <text class="fig-muted" x="422" y="58" font-size="11">j = 2: 38 &lt; 49 (k = 2)；j = 3: 65 &gt; 38</text>
    <text class="fig-accent" x="422" y="74" font-size="11">j = 4: 13 &lt; 38 (k = 4)；j = 5: 27 &gt; 13</text>
    <text class="fig-green" x="24" y="130" font-size="11.5">交换落位</text>
    <g font-size="12" text-anchor="middle">
      <rect class="fig-box-green" x="112" y="112" width="52" height="28" rx="4"/><text class="fig-green" x="138" y="130">13</text>
      <rect class="fig-box" x="172" y="112" width="52" height="28" rx="4"/><text class="fig-label" x="198" y="130">38</text>
      <rect class="fig-box" x="232" y="112" width="52" height="28" rx="4"/><text class="fig-label" x="258" y="130">65</text>
      <rect class="fig-box" x="292" y="112" width="52" height="28" rx="4"/><text class="fig-label" x="318" y="130">49</text>
      <rect class="fig-box" x="352" y="112" width="52" height="28" rx="4"/><text class="fig-label" x="378" y="130">27</text>
    </g>
    <text class="fig-green" x="422" y="130" font-size="11">第 1 趟确定最小值 13（比较 4 次，交换 1 次）</text>
    <line class="fig-divider" x1="24" y1="154" x2="676" y2="154"/>
    <text class="fig-title" x="24" y="174" font-size="12">不稳定反例：[8₁, 8₂, 2] 因长距离交换颠倒相等元素次序</text>
    <text class="fig-muted" x="110" y="196" text-anchor="middle" font-size="11">初始序列（8₁ 在 8₂ 前）</text>
    <g font-size="12" text-anchor="middle">
      <rect class="fig-box-blue" x="36" y="204" width="44" height="28" rx="4"/><text class="fig-blue" x="58" y="222">8₁</text>
      <rect class="fig-box-purple" x="88" y="204" width="44" height="28" rx="4"/><text class="fig-purple" x="110" y="222">8₂</text>
      <rect class="fig-box-orange" x="140" y="204" width="44" height="28" rx="4"/><text class="fig-orange" x="162" y="222">2</text>
    </g>
    <line x1="196" y1="218" x2="232" y2="218" stroke="var(--sl-color-gray-4)" stroke-width="1.4" marker-end="url(#wz-w5-arr-16)"/>
    <text class="fig-accent" x="318" y="196" text-anchor="middle" font-size="11">第 1 趟选中最小 k = 3</text>
    <path d="M 266 232 Q 318 258 370 232" fill="none" stroke="var(--sl-color-red)" stroke-width="1.35" marker-start="url(#wz-w5-arr-16)" marker-end="url(#wz-w5-arr-16)"/>
    <g font-size="12" text-anchor="middle">
      <rect class="fig-box-blue" x="244" y="204" width="44" height="28" rx="4"/><text class="fig-blue" x="266" y="222">8₁</text>
      <rect class="fig-box-purple" x="296" y="204" width="44" height="28" rx="4"/><text class="fig-purple" x="318" y="222">8₂</text>
      <rect class="fig-box-orange" x="348" y="204" width="44" height="28" rx="4"/><text class="fig-orange" x="370" y="222">2</text>
    </g>
    <rect class="fig-box" x="276" y="242" width="84" height="18" rx="4"/>
    <text class="fig-red" x="318" y="255" text-anchor="middle" font-size="10.5">跨过 8₂ 交换</text>
    <line x1="406" y1="218" x2="442" y2="218" stroke="var(--sl-color-gray-4)" stroke-width="1.4" marker-end="url(#wz-w5-arr-16)"/>
    <text class="fig-green" x="548" y="196" text-anchor="middle" font-size="11">第 1 趟后（及最终结果）</text>
    <g font-size="12" text-anchor="middle">
      <rect class="fig-box-green" x="474" y="204" width="44" height="28" rx="4"/><text class="fig-green" x="496" y="222">2</text>
      <rect class="fig-box-purple" x="526" y="204" width="44" height="28" rx="4"/><text class="fig-purple" x="548" y="222">8₂</text>
      <rect class="fig-box-blue" x="578" y="204" width="44" height="28" rx="4"/><text class="fig-blue" x="600" y="222">8₁</text>
    </g>
    <text class="fig-red" x="548" y="254" text-anchor="middle" font-size="11">8₂ 跑到了 8₁ 前面 → 不稳定！</text>
    <rect class="fig-box-subtle" x="24" y="276" width="652" height="30" rx="5"/>
    <text class="fig-muted" x="350" y="295" text-anchor="middle" font-size="11.5">比较次数恒为 n(n−1)/2（与初态无关），移动少；若把“交换”改为“元素后移再插入”即可稳定化</text>
  </svg>
  <figcaption>简单选择排序过程与不稳定反例：每趟打擂台仅交换 1 次，但长距离交换会跨越相等元素</figcaption>
</figure>

### 堆的定义与筛选调整

**堆**：$n$ 个元素的序列 $\{k_1,k_2,\dots,k_n\}$，若满足

- $k_i \le k_{2i}$ 且 $k_i \le k_{2i+1}$ → **小根堆**（根最小）；
- $k_i \ge k_{2i}$ 且 $k_i \ge k_{2i+1}$ → **大根堆**（根最大）。

（均允许取等号。）

**本质是一棵完全二叉树**：按“从上到下、从左到右、根为 1 号”的层序编号，由二叉树性质 5，$i$ 的左孩子是 $2i$、右孩子是 $2i+1$。堆条件即“任一非叶子结点的值不大于（或不小于）其左右孩子”。因此**堆在逻辑上是完全二叉树，在存储上是顺序表**。

<figure class="cpd-figure not-content" id="wz-w5-fig-15">
  <svg viewBox="0 0 700 364" role="img" aria-labelledby="wz-w5-title-15">
    <title id="wz-w5-title-15">小根堆的完全二叉树形态与顺序表下标对应</title>
    <text class="fig-title" x="24" y="22" font-size="13">小根堆：完全二叉树层序编号 ≡ 顺序表下标（1-based）</text>
    <g class="fig-line">
      <line x1="350" y1="56" x2="220" y2="120"/><line x1="350" y1="56" x2="480" y2="120"/>
      <line x1="220" y1="120" x2="150" y2="184"/><line x1="220" y1="120" x2="290" y2="184"/>
      <line x1="480" y1="120" x2="410" y2="184"/><line x1="480" y1="120" x2="550" y2="184"/>
      <line x1="150" y1="184" x2="110" y2="248"/>
    </g>
    <circle class="fig-box-accent" cx="350" cy="56" r="20"/>
    <g class="fig-box-blue">
      <circle cx="220" cy="120" r="20"/><circle cx="480" cy="120" r="20"/>
      <circle cx="150" cy="184" r="20"/><circle cx="290" cy="184" r="20"/>
      <circle cx="410" cy="184" r="20"/><circle cx="550" cy="184" r="20"/>
      <circle cx="110" cy="248" r="20"/>
    </g>
    <g font-size="13" text-anchor="middle">
      <text class="fig-accent" x="350" y="61">13</text>
      <text class="fig-blue" x="220" y="125">38</text><text class="fig-blue" x="480" y="125">27</text>
      <text class="fig-blue" x="150" y="189">49</text><text class="fig-blue" x="290" y="189">76</text>
      <text class="fig-blue" x="410" y="189">65</text><text class="fig-blue" x="550" y="189">49</text>
      <text class="fig-blue" x="110" y="253">97</text>
    </g>
    <g class="fig-muted" font-size="10.5" text-anchor="middle">
      <text x="376" y="46">1</text><text x="194" y="110">2</text><text x="506" y="110">3</text>
      <text x="124" y="174">4</text><text x="316" y="174">5</text><text x="384" y="174">6</text>
      <text x="576" y="174">7</text><text x="84" y="238">8</text>
    </g>
    <g class="fig-box">
      <rect class="fig-box-accent" x="110" y="294" width="60" height="32"/>
      <rect x="170" y="294" width="60" height="32"/><rect x="230" y="294" width="60" height="32"/>
      <rect x="290" y="294" width="60" height="32"/><rect x="350" y="294" width="60" height="32"/>
      <rect x="410" y="294" width="60" height="32"/><rect x="470" y="294" width="60" height="32"/>
      <rect x="530" y="294" width="60" height="32"/>
    </g>
    <g font-size="12.5" text-anchor="middle">
      <text class="fig-accent" x="140" y="315">13</text>
      <text class="fig-label" x="200" y="315">38</text><text class="fig-label" x="260" y="315">27</text>
      <text class="fig-label" x="320" y="315">49</text><text class="fig-label" x="380" y="315">76</text>
      <text class="fig-label" x="440" y="315">65</text><text class="fig-label" x="500" y="315">49</text>
      <text class="fig-label" x="560" y="315">97</text>
    </g>
    <g class="fig-muted" font-size="11" text-anchor="middle">
      <text x="140" y="288">1</text><text x="200" y="288">2</text><text x="260" y="288">3</text><text x="320" y="288">4</text>
      <text x="380" y="288">5</text><text x="440" y="288">6</text><text x="500" y="288">7</text><text x="560" y="288">8</text>
    </g>
    <text class="fig-muted" x="350" y="346" text-anchor="middle" font-size="11.5">结点 i 的左右孩子为 2i 与 2i + 1（如结点 3 值为 27，左右孩子为结点 6 的 65 与结点 7 的 49）</text>
  </svg>
  <figcaption>小根堆存储对照：kᵢ ≤ k₂ᵢ 且 kᵢ ≤ k₂ᵢ₊₁，堆顶元素 13 为全表最小值</figcaption>
</figure>

**判断是否为堆**：把序列按层序摆成完全二叉树，逐个检查每个非叶子结点是否都满足堆条件。只有“全部满足”才是堆；有大有小、忽大忽小都不算。

**筛选（堆调整）**：输出堆顶后，堆的性质被破坏，需要恢复。

1. 用**最后一个元素**（层序编号最大的结点，即第 $n$ 号）顶替堆顶。
2. 用它与左右孩子中**较小者**（小根堆）比较：若比孩子大，就与较小孩子交换，把它往下压一层。
3. 重复第 2 步，直到它**成为叶子**（没有孩子），调整结束。

大根堆完全对称：每次与左右孩子中**较大者**交换。

```c
void HeapAdjust(SqList &L, int s, int m) {    /* 小根堆：把 r[s] 向下筛到合适位置 */
    RecordType rc = L.r[s];
    for (int j = 2 * s; j <= m; j *= 2) {
        if (j < m && L.r[j+1].key < L.r[j].key) j++;   /* 取较小的孩子 */
        if (rc.key <= L.r[j].key) break;               /* 已满足堆序，停止 */
        L.r[s] = L.r[j];
        s = j;
    }
    L.r[s] = rc;
}
```

> **注意**：被筛元素**必须一直下到叶子**（或提前满足堆序）才算完，只比较一层是不够的。筛选一次的时间不超过 $O(\log n)$（完全二叉树高度）。

### 建堆与堆排序

**建堆（初始堆）**：从一个无序序列出发，反复筛选即可得到堆。依据是：

- 单个结点本身就是堆；
- 完全二叉树中所有**叶子**都没有孩子，以叶子为根的子树**已经是堆**，无需调整；
- 因此只需从**最后一个非叶子结点**开始，依次向前到根，对每个结点执行一次筛选。

最后一个非叶子结点的编号是 $\left\lfloor n/2 \right\rfloor$（最后一个叶子是 $n$，其双亲为 $\lfloor n/2 \rfloor$）。所以建堆循环为

```c
for (int i = L.length / 2; i >= 1; i--)
    HeapAdjust(L, i, L.length);      /* 自底向上，逐个把子树调成堆 */
```

例：对 49, 38, 65, 97, 76, 13, 27, 49 建小根堆，$n=8$，从结点 4 开始：

- 结点 4（97）与孩子 8（49）交换 → 49 上去、97 下来；
- 结点 3（65）与较小的孩子 6（13）交换 → 13 上去；
- 结点 2（38）已小于两个孩子 49、76，不动；
- 结点 1（49）与较小的孩子 3（13）交换，49 落到结点 3 后继续与孩子 6（65）、7（27）比较，再与 27 交换，49 下到叶子 7。

最终得到小根堆 13, 38, 27, 49, 76, 65, 49, 97。**每次交换都同时在顺序表和完全二叉树上同步完成**，二者是同一份数据的两种视图。

**堆排序**：建好堆后，堆顶就是最小值（小根堆）或最大值（大根堆）。反复“取堆顶 → 用末尾元素顶替 → 筛选”，每取一次就得到一个有序元素，$n-1$ 次后全部有序。

```c
void HeapSort(SqList &L) {
    for (int i = L.length / 2; i >= 1; i--)      /* 建初始堆，O(n) */
        HeapAdjust(L, i, L.length);
    for (int i = L.length; i > 1; i--) {
        swap(L.r[1], L.r[i]);                    /* 堆顶（最值）换到当前末尾，即最终位置 */
        HeapAdjust(L, 1, i - 1);                 /* 剩余 i-1 个元素重新筛选成堆 */
    }
}
```

> **注意**：原地交换的写法里，**大根堆得到升序**（最大值换到末尾），**小根堆得到降序**。若用小根堆又要输出升序，则需把每次取出的最小值依次放到序列前端（或先降序再逆置），不能直接“堆顶换末尾”。课程中“建小根堆、逐个输出堆顶”得到的是从小到大的输出序列。

<figure class="cpd-figure not-content" id="wz-w5-fig-19">
  <svg viewBox="0 0 700 452" role="img" aria-labelledby="wz-w5-title-19">
    <title id="wz-w5-title-19">建堆与堆排序演进：自底向上从 ⌊n/2⌋ 建小根堆与堆顶输出后向下筛选</title>
    <defs>
      <marker id="wz-w5-arr-19" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
        <path d="M 1 1.5 L 8.5 5 L 1 8.5 z" fill="context-stroke" stroke="none"/>
      </marker>
    </defs>
    <text class="fig-title" x="24" y="22" font-size="12.5">建堆与堆排序演进（n = 8，小根堆）：从 ⌊n/2⌋ = 4 自底向上建堆 + 堆顶输出后向下筛选</text>
    <text class="fig-blue" x="24" y="42" font-size="11.5">阶段一：自底向上建初始小根堆（i = 4 → 3 → 2 → 1）</text>
    <g class="fig-line">
      <line x1="120" y1="66" x2="74" y2="100"/><line x1="120" y1="66" x2="166" y2="100"/>
      <line x1="74" y1="100" x2="50" y2="134"/><line x1="74" y1="100" x2="98" y2="134"/>
      <line x1="166" y1="100" x2="142" y2="134"/><line x1="166" y1="100" x2="190" y2="134"/>
      <line x1="50" y1="134" x2="34" y2="168"/>
      <line x1="350" y1="66" x2="304" y2="100"/><line x1="350" y1="66" x2="396" y2="100"/>
      <line x1="304" y1="100" x2="280" y2="134"/><line x1="304" y1="100" x2="328" y2="134"/>
      <line x1="396" y1="100" x2="372" y2="134"/><line x1="396" y1="100" x2="420" y2="134"/>
      <line x1="280" y1="134" x2="264" y2="168"/>
      <line x1="580" y1="66" x2="534" y2="100"/><line x1="580" y1="66" x2="626" y2="100"/>
      <line x1="534" y1="100" x2="510" y2="134"/><line x1="534" y1="100" x2="558" y2="134"/>
      <line x1="626" y1="100" x2="602" y2="134"/><line x1="626" y1="100" x2="650" y2="134"/>
      <line x1="510" y1="134" x2="494" y2="168"/>
    </g>
    <path d="M 38 134 Q 18 148 22 162" fill="none" stroke="var(--sl-color-accent)" stroke-width="1.25" marker-start="url(#wz-w5-arr-19)" marker-end="url(#wz-w5-arr-19)"/>
    <path d="M 156 108 Q 140 112 136 122" fill="none" stroke="var(--sl-color-accent)" stroke-width="1.25" marker-start="url(#wz-w5-arr-19)" marker-end="url(#wz-w5-arr-19)"/>
    <path d="M 364 68 Q 392 74 394 86" fill="none" stroke="var(--sl-color-orange)" stroke-width="1.35" marker-end="url(#wz-w5-arr-19)"/>
    <path d="M 408 104 Q 426 112 422 122" fill="none" stroke="var(--sl-color-orange)" stroke-width="1.35" marker-end="url(#wz-w5-arr-19)"/>
    <g font-size="10.5" text-anchor="middle">
      <circle class="fig-box" cx="120" cy="66" r="12"/><text class="fig-label" x="120" y="70">49</text>
      <circle class="fig-box" cx="74" cy="100" r="12"/><text class="fig-label" x="74" y="104">38</text>
      <circle class="fig-box-orange" cx="166" cy="100" r="12"/><text class="fig-orange" x="166" y="104">65</text>
      <circle class="fig-box-orange" cx="50" cy="134" r="12"/><text class="fig-orange" x="50" y="138">97</text>
      <circle class="fig-box" cx="98" cy="134" r="12"/><text class="fig-label" x="98" y="138">76</text>
      <circle class="fig-box-accent" cx="142" cy="134" r="12"/><text class="fig-accent" x="142" y="138">13</text>
      <circle class="fig-box" cx="190" cy="134" r="12"/><text class="fig-label" x="190" y="138">27</text>
      <circle class="fig-box-accent" cx="34" cy="168" r="12"/><text class="fig-accent" x="34" y="172">49'</text>
      <circle class="fig-box-orange" cx="350" cy="66" r="12"/><text class="fig-orange" x="350" y="70">49</text>
      <circle class="fig-box" cx="304" cy="100" r="12"/><text class="fig-label" x="304" y="104">38</text>
      <circle class="fig-box-accent" cx="396" cy="100" r="12"/><text class="fig-accent" x="396" y="104">13</text>
      <circle class="fig-box" cx="280" cy="134" r="12"/><text class="fig-label" x="280" y="138">49'</text>
      <circle class="fig-box" cx="328" cy="134" r="12"/><text class="fig-label" x="328" y="138">76</text>
      <circle class="fig-box" cx="372" cy="134" r="12"/><text class="fig-label" x="372" y="138">65</text>
      <circle class="fig-box-accent" cx="420" cy="134" r="12"/><text class="fig-accent" x="420" y="138">27</text>
      <circle class="fig-box" cx="264" cy="168" r="12"/><text class="fig-label" x="264" y="172">97</text>
      <circle class="fig-box-green" cx="580" cy="66" r="12"/><text class="fig-green" x="580" y="70">13</text>
      <circle class="fig-box" cx="534" cy="100" r="12"/><text class="fig-label" x="534" y="104">38</text>
      <circle class="fig-box-blue" cx="626" cy="100" r="12"/><text class="fig-blue" x="626" y="104">27</text>
      <circle class="fig-box" cx="510" cy="134" r="12"/><text class="fig-label" x="510" y="138">49'</text>
      <circle class="fig-box" cx="558" cy="134" r="12"/><text class="fig-label" x="558" y="138">76</text>
      <circle class="fig-box" cx="602" cy="134" r="12"/><text class="fig-label" x="602" y="138">65</text>
      <circle class="fig-box-orange" cx="650" cy="134" r="12"/><text class="fig-orange" x="650" y="138">49</text>
      <circle class="fig-box" cx="494" cy="168" r="12"/><text class="fig-label" x="494" y="172">97</text>
    </g>
    <line x1="210" y1="112" x2="244" y2="112" stroke="var(--sl-color-gray-4)" stroke-width="1.4" marker-end="url(#wz-w5-arr-19)"/>
    <line x1="440" y1="112" x2="474" y2="112" stroke="var(--sl-color-gray-4)" stroke-width="1.4" marker-end="url(#wz-w5-arr-19)"/>
    <g font-size="10.5" text-anchor="middle">
      <text class="fig-muted" x="120" y="196">① i = 4: 97↔49'；i = 3: 65↔13</text>
      <text class="fig-muted" x="120" y="210">i = 2: 38 已满足堆序不动</text>
      <text class="fig-orange" x="350" y="196">② i = 1: 根 49 沿较小孩子下沉</text>
      <text class="fig-muted" x="350" y="210">先与 13 换，再与 27 换到叶子 7</text>
      <text class="fig-green" x="580" y="196">③ 初始小根堆建成（O(n)）</text>
      <text class="fig-muted" x="580" y="210">[13, 38, 27, 49', 76, 65, 49, 97]</text>
    </g>
    <line class="fig-divider" x1="24" y1="224" x2="676" y2="224"/>
    <text class="fig-green" x="24" y="242" font-size="11.5">阶段二：输出堆顶 + 末尾元素顶替 + HeapAdjust(1, i − 1) 向下筛选</text>
    <g class="fig-line">
      <line x1="120" y1="266" x2="74" y2="300"/><line x1="120" y1="266" x2="166" y2="300"/>
      <line x1="74" y1="300" x2="50" y2="334"/><line x1="74" y1="300" x2="98" y2="334"/>
      <line x1="166" y1="300" x2="142" y2="334"/><line x1="166" y1="300" x2="190" y2="334"/>
      <line x1="350" y1="266" x2="304" y2="300"/><line x1="350" y1="266" x2="396" y2="300"/>
      <line x1="304" y1="300" x2="280" y2="334"/><line x1="304" y1="300" x2="328" y2="334"/>
      <line x1="396" y1="300" x2="372" y2="334"/><line x1="396" y1="300" x2="420" y2="334"/>
      <line x1="580" y1="266" x2="534" y2="300"/><line x1="580" y1="266" x2="626" y2="300"/>
      <line x1="534" y1="300" x2="510" y2="334"/><line x1="534" y1="300" x2="558" y2="334"/>
      <line x1="626" y1="300" x2="602" y2="334"/><line x1="626" y1="300" x2="650" y2="334"/>
    </g>
    <g class="fig-line-dashed">
      <line x1="50" y1="334" x2="34" y2="368"/>
      <line x1="280" y1="334" x2="264" y2="368"/>
      <line x1="510" y1="334" x2="494" y2="368"/>
    </g>
    <path d="M 134 268 Q 162 274 164 286" fill="none" stroke="var(--sl-color-red)" stroke-width="1.35" marker-end="url(#wz-w5-arr-19)"/>
    <path d="M 408 304 Q 426 312 422 322" fill="none" stroke="var(--sl-color-orange)" stroke-width="1.35" marker-end="url(#wz-w5-arr-19)"/>
    <g font-size="10.5" text-anchor="middle">
      <circle class="fig-box-red" cx="120" cy="266" r="12"/><text class="fig-red" x="120" y="270">97</text>
      <circle class="fig-box" cx="74" cy="300" r="12"/><text class="fig-label" x="74" y="304">38</text>
      <circle class="fig-box-accent" cx="166" cy="300" r="12"/><text class="fig-accent" x="166" y="304">27</text>
      <circle class="fig-box" cx="50" cy="334" r="12"/><text class="fig-label" x="50" y="338">49'</text>
      <circle class="fig-box" cx="98" cy="334" r="12"/><text class="fig-label" x="98" y="338">76</text>
      <circle class="fig-box" cx="142" cy="334" r="12"/><text class="fig-label" x="142" y="338">65</text>
      <circle class="fig-box" cx="190" cy="334" r="12"/><text class="fig-label" x="190" y="338">49</text>
      <rect class="fig-box-green" x="22" y="356" width="24" height="22" rx="4"/><text class="fig-green" x="34" y="371">13</text>
      <circle class="fig-box-blue" cx="350" cy="266" r="12"/><text class="fig-blue" x="350" y="270">27</text>
      <circle class="fig-box" cx="304" cy="300" r="12"/><text class="fig-label" x="304" y="304">38</text>
      <circle class="fig-box-orange" cx="396" cy="300" r="12"/><text class="fig-orange" x="396" y="304">97</text>
      <circle class="fig-box" cx="280" cy="334" r="12"/><text class="fig-label" x="280" y="338">49'</text>
      <circle class="fig-box" cx="328" cy="334" r="12"/><text class="fig-label" x="328" y="338">76</text>
      <circle class="fig-box" cx="372" cy="334" r="12"/><text class="fig-label" x="372" y="338">65</text>
      <circle class="fig-box-accent" cx="420" cy="334" r="12"/><text class="fig-accent" x="420" y="338">49</text>
      <rect class="fig-box-green" x="252" y="356" width="24" height="22" rx="4"/><text class="fig-green" x="264" y="371">13</text>
      <circle class="fig-box-green" cx="580" cy="266" r="12"/><text class="fig-green" x="580" y="270">27</text>
      <circle class="fig-box" cx="534" cy="300" r="12"/><text class="fig-label" x="534" y="304">38</text>
      <circle class="fig-box-blue" cx="626" cy="300" r="12"/><text class="fig-blue" x="626" y="304">49</text>
      <circle class="fig-box" cx="510" cy="334" r="12"/><text class="fig-label" x="510" y="338">49'</text>
      <circle class="fig-box" cx="558" cy="334" r="12"/><text class="fig-label" x="558" y="338">76</text>
      <circle class="fig-box" cx="602" cy="334" r="12"/><text class="fig-label" x="602" y="338">65</text>
      <circle class="fig-box-red" cx="650" cy="334" r="12"/><text class="fig-red" x="650" y="338">97</text>
      <rect class="fig-box-green" x="482" y="356" width="24" height="22" rx="4"/><text class="fig-green" x="494" y="371">13</text>
    </g>
    <line x1="210" y1="312" x2="244" y2="312" stroke="var(--sl-color-gray-4)" stroke-width="1.4" marker-end="url(#wz-w5-arr-19)"/>
    <line x1="440" y1="312" x2="474" y2="312" stroke="var(--sl-color-gray-4)" stroke-width="1.4" marker-end="url(#wz-w5-arr-19)"/>
    <g font-size="10.5" text-anchor="middle">
      <text class="fig-red" x="120" y="394">④ 13 出堆，末位 97 顶替到根</text>
      <text class="fig-orange" x="350" y="394">⑤ HeapAdjust(1, 7)：97 连沉两层</text>
      <text class="fig-green" x="580" y="394">⑥ 新堆顶 27 就绪，堆长缩为 7</text>
    </g>
    <rect class="fig-box-subtle" x="24" y="408" width="652" height="28" rx="5"/>
    <text class="fig-muted" x="350" y="426" text-anchor="middle" font-size="11">建堆 O(n) + 共 n − 1 趟筛选（每趟 O(log n)）→ 总时间恒为 O(n log n)，空间 O(1)，跨层交换导致不稳定</text>
  </svg>
  <figcaption>建堆与堆排序完整过程：自底向上建堆只需从 ⌊n/2⌋ 开始调整，排序阶段每趟确定 1 个最值并缩减堆长</figcaption>
</figure>

**性能分析**：

- 建初始堆：$O(n)$（自底向上筛选的总代价是线性的）。
- 排序阶段：$n-1$ 次筛选，每次不超过 $O(\log n)$，故 $O(n\log n)$。
- 总时间 $O(n\log n)$，且**最好、最坏、平均都一样**——与初始序列是正序还是逆序**无关**，这是堆排序相对快速排序的最大优势。
- 空间：只用交换时的 1 个临时单元，$O(1)$，原地排序。
- **不稳定**：筛选中的交换是跨层的远距离交换，相等元素相对次序会被打乱。
- 由于建堆与调整的常数较大，堆排序更适合**记录数较大**的场合。

> **★考点**：建堆从 $\lfloor n/2\rfloor$ 开始、向前到 1；堆排序每趟把堆顶送到末尾并缩小堆的范围，每趟**确定一个最值的最终位置**。

> **交互演示**：[简单选择排序与堆排序](/lab/chapter-10/#lab-selection)

### 归并排序

**归并**：把两个或两个以上**有序**子序列合并成一个有序序列。内部排序常用**二路归并**——每次把两个相邻的有序段合并成一个。

设两个相邻有序段为 `r[low..mid]` 与 `r[mid+1..high]`，合并时用两个指针 `i`、`j` 分别指向两段首元素，比较二者关键字，小者放入辅助数组 `T` 的 `k` 位置，然后指针后移；某一段耗尽后，把另一段剩余元素**直接整体搬过去**。

```c
void Merge(SqList &L, SqList &T, int low, int mid, int high) {
    int i = low, j = mid + 1, k = low;
    while (i <= mid && j <= high) {
        if (L.r[i].key <= L.r[j].key) T.r[k++] = L.r[i++];  /* 取等号 → 稳定 */
        else                          T.r[k++] = L.r[j++];
    }
    while (i <= mid)  T.r[k++] = L.r[i++];
    while (j <= high) T.r[k++] = L.r[j++];
}
```

**过程拆解**：合并 `A=[13,27,49]` 与 `B=[38,65,76,97]`：

| 步骤 | 比较 | 取出 | 结果 `T` |
|:---:|:---|:---|:---|
| 1 | 13 < 38 | A 的 13 | `[13]` |
| 2 | 27 < 38 | A 的 27 | `[13,27]` |
| 3 | 49 > 38 | B 的 38 | `[13,27,38]` |
| 4 | 49 < 65 | A 的 49 | `[13,27,38,49]` |
| 5 | A 耗尽 | 搬 B 剩余 | `[13,27,38,49,65,76,97]` |

每次只比较两个队首，取小者；某段耗尽后另一段整体搬过去，所以合并本身是线性的。

<figure class="cpd-figure not-content" id="wz-w5-fig-17">
  <svg viewBox="0 0 700 246" role="img" aria-labelledby="wz-w5-title-17">
    <title id="wz-w5-title-17">二路归并排序归并树（7 记录 3 趟合并）</title>
    <text class="fig-title" x="24" y="22" font-size="12.5">二路归并排序归并树（7 记录 3 趟合并）：每趟扫描合并 O(n)，树高 ⌈log₂n⌉</text>
    <text class="fig-muted" x="24" y="60" font-size="11.5">初态（长度 1）</text>
    <g class="fig-line">
      <line x1="162" y1="68" x2="188" y2="94"/><line x1="214" y1="68" x2="188" y2="94"/>
      <line x1="284" y1="68" x2="310" y2="94"/><line x1="336" y1="68" x2="310" y2="94"/>
      <line x1="406" y1="68" x2="432" y2="94"/><line x1="458" y1="68" x2="432" y2="94"/>
      <line x1="536" y1="68" x2="536" y2="94"/>
      <line x1="188" y1="122" x2="249" y2="148"/><line x1="310" y1="122" x2="249" y2="148"/>
      <line x1="432" y1="122" x2="484" y2="148"/><line x1="536" y1="122" x2="484" y2="148"/>
      <line x1="249" y1="176" x2="366" y2="198"/><line x1="484" y1="176" x2="366" y2="198"/>
    </g>
    <g font-size="12" text-anchor="middle">
      <rect class="fig-box" x="140" y="42" width="44" height="26" rx="4"/><text class="fig-label" x="162" y="60">49</text>
      <rect class="fig-box" x="192" y="42" width="44" height="26" rx="4"/><text class="fig-label" x="214" y="60">38</text>
      <rect class="fig-box" x="262" y="42" width="44" height="26" rx="4"/><text class="fig-label" x="284" y="60">65</text>
      <rect class="fig-box" x="314" y="42" width="44" height="26" rx="4"/><text class="fig-label" x="336" y="60">97</text>
      <rect class="fig-box" x="384" y="42" width="44" height="26" rx="4"/><text class="fig-label" x="406" y="60">76</text>
      <rect class="fig-box" x="436" y="42" width="44" height="26" rx="4"/><text class="fig-label" x="458" y="60">13</text>
      <rect class="fig-box" x="514" y="42" width="44" height="26" rx="4"/><text class="fig-label" x="536" y="60">27</text>
    </g>
    <text class="fig-muted" x="24" y="114" font-size="11.5">第 1 趟合并</text>
    <g font-size="12" text-anchor="middle">
      <rect class="fig-box-blue" x="144" y="96" width="88" height="26" rx="4"/><text class="fig-blue" x="188" y="114">[38, 49]</text>
      <rect class="fig-box-blue" x="266" y="96" width="88" height="26" rx="4"/><text class="fig-blue" x="310" y="114">[65, 97]</text>
      <rect class="fig-box-orange" x="388" y="96" width="88" height="26" rx="4"/><text class="fig-orange" x="432" y="114">[13, 76]</text>
      <rect class="fig-box-orange" x="514" y="96" width="44" height="26" rx="4"/><text class="fig-orange" x="536" y="114">[27]</text>
    </g>
    <text class="fig-muted" x="24" y="168" font-size="11.5">第 2 趟合并</text>
    <g font-size="12" text-anchor="middle">
      <rect class="fig-box-accent" x="154" y="150" width="190" height="26" rx="4"/><text class="fig-accent" x="249" y="168">[38, 49, 65, 97]</text>
      <rect class="fig-box-accent" x="400" y="150" width="168" height="26" rx="4"/><text class="fig-accent" x="484" y="168">[13, 27, 76]</text>
    </g>
    <text class="fig-green" x="24" y="216" font-size="11.5">第 3 趟有序</text>
    <rect class="fig-box-green" x="196" y="198" width="340" height="28" rx="4"/>
    <text class="fig-green" x="366" y="217" text-anchor="middle" font-size="12.5">[13, 27, 38, 49, 65, 76, 97]（稳定，O(n log n)）</text>
  </svg>
  <figcaption>二路归并树：共 ⌈log₂n⌉ 趟归并，每趟 O(n) 扫描合并，辅助空间 O(n)</figcaption>
</figure>

整个归并排序：先让每个元素自成一个长度为 1 的有序段（两两归并成长度 2，再 4、8……），直到合成一个长度为 $n$ 的有序段。这一过程画出来是一棵倒立的**归并树**，树高即归并趟数：

$$
\lceil \log_2 n \rceil
$$

**性能分析**：

- 每趟归并要把 $n$ 个元素扫一遍、搬一遍，共 $\lceil \log_2 n\rceil$ 趟，故最好、最坏、平均时间**都是** $O(n\log n)$，与初始状态无关。
- 空间：需要一个与原数组等大的**辅助数组**存放合并结果，$O(n)$——**不是原地排序**，这是归并排序的主要缺点。
- **稳定**：合并时相等元素优先取左段的（`<=`），左段元素原本就在前面，相对次序不变。

> **注意**：归并的两个子序列必须是**相邻且各自有序**的；合并不是“排序”本身，它只负责把两段有序数据并成一段。

### 基数排序

基数排序**不做关键字比较**，靠“**分配**”与“**收集**”两步完成，又称桶排序、箱排序。

- **分配**：按关键字某一位的取值 $k$，把记录放进第 $k$ 个箱子（桶）。
- **收集**：按桶号 0,1,2,… 的顺序把各桶记录依次取出、首尾相接。

由于桶的个数必须有限，基数排序要求关键字**取值范围有限**——十进制数每位只有 0–9，准备 10 个桶即可。

**做法（低位优先）**：先按**个位**分配收集，再按**十位**，最后按**百位**；每趟都在上一趟的结果上进行。

例：614, 738, 921, 485, 637, 101, 215, 530, 790, 306。

1. 按个位入桶、按桶号收集 → 个位有序：530, 790, 921, 101, 614, 485, 215, 306, 637, 738。
2. 按十位入桶收集 → 十位有序（个位次序被保留）。
3. 按百位入桶收集 → 整体有序：101, 215, 306, 485, 530, 614, 637, 738, 790, 921。

<figure class="cpd-figure not-content" id="wz-w5-fig-18">
  <svg viewBox="0 0 700 234" role="img" aria-labelledby="wz-w5-title-18">
    <title id="wz-w5-title-18">基数排序三趟低位优先（LSD）分配与收集结果演进</title>
    <text class="fig-title" x="24" y="22" font-size="12.5">三位十进制数 LSD 基数排序：按“个位 → 十位 → 百位”依次稳定分配收集</text>
    <text class="fig-muted" x="24" y="54" font-size="11.5">初始序列</text>
    <rect class="fig-box" x="96" y="34" width="580" height="30" rx="4"/>
    <text class="fig-label" x="386" y="53" text-anchor="middle" font-size="12">614, 738, 921, 485, 637, 101, 215, 530, 790, 306</text>
    <text class="fig-blue" x="24" y="98" font-size="11.5">① 按个位</text>
    <rect class="fig-box-blue" x="96" y="78" width="580" height="30" rx="4"/>
    <text class="fig-blue" x="386" y="97" text-anchor="middle" font-size="12">53[0], 79[0], 92[1], 10[1], 61[4], 48[5], 21[5], 30[6], 63[7], 73[8]</text>
    <text class="fig-orange" x="24" y="142" font-size="11.5">② 按十位</text>
    <rect class="fig-box-orange" x="96" y="122" width="580" height="30" rx="4"/>
    <text class="fig-orange" x="386" y="141" text-anchor="middle" font-size="12">1[0]1, 3[0]6, 6[1]4, 2[1]5, 9[2]1, 5[3]0, 6[3]7, 7[3]8, 4[8]5, 7[9]0</text>
    <text class="fig-green" x="24" y="186" font-size="11.5">③ 按百位</text>
    <rect class="fig-box-green" x="96" y="166" width="580" height="30" rx="4"/>
    <text class="fig-green" x="386" y="185" text-anchor="middle" font-size="12">[1]01, [2]15, [3]06, [4]85, [5]30, [6]14, [6]37, [7]38, [7]90, [9]21</text>
    <text class="fig-muted" x="350" y="216" text-anchor="middle" font-size="11.5">同桶内保持先入先出（稳定）：如十位均为 3 的 530、637、738 保留了第 1 趟排好的个位次序</text>
  </svg>
  <figcaption>LSD 基数排序逐趟演进：低位已排好的相对顺序在高位同桶内被完整保留</figcaption>
</figure>

**为什么可行**：每一趟都是**稳定**的分配收集，低位排好的次序在高位相同的记录之间被保留下来，等价于“按个位、十位、百位依次做稳定排序”，也就是多关键字排序。扑克牌同理：先按花色分 4 桶，再按点数分 13 桶。

**性能分析**（$n$ 个记录，$m$ 个桶，$k$ 个关键字位/趟数）：

- 每趟分配需把 $n$ 个记录放入桶，收集需扫 $m$ 个桶，一趟 $O(n+m)$；共 $k$ 趟：
$$
T = O\big(k\,(n+m)\big)
$$
- 最好情况一趟即完成，$O(n+m)$；最坏、平均为 $O(k(n+m))$。对 $n$ 而言是**线性阶**，比 $O(n\log n)$ 还快。
- 空间：$m$ 个桶 + 存放 $n$ 个记录的空间，$O(n+m)$。
- **稳定**。
- 适用条件苛刻：关键字必须是**有限范围内的整数/可分位**（如年份、月份、日期、学号）。取值范围太大（桶数爆炸）时不可用。

> **★考点**：基数排序时间 $O(k(n+m))$、空间 $O(n+m)$、稳定、不基于比较；这是它区别于其它所有内部排序的地方。

> **交互演示**：[归并排序与 LSD 基数排序](/lab/chapter-10/#lab-merge)

### 各种排序方法的比较

**时间性能**（三类）：

| 类别 | 算法 | 特点 |
| --- | --- | --- |
| $O(n\log n)$ 先进 | 快速、堆、归并 | 快速排序平均最快，但用递归、空间开销大 |
| $O(n^2)$ 简单 | 直接插入、冒泡、简单选择 | 直接插入在同类中最快；冒泡在基本有序时也快；简单选择移动少但比较次数固定 |
| 线性阶 | 基数排序 | 最快，但只适用于关键字取值范围有限的情况 |

**完整对比表**（`插入`=直接插入，`折半`=折半插入，`选择`=简单选择）：

| 算法 | 平均 | 最好 | 最坏 |
|:----:|:----:|:----:|:----:|
| 插入 | $O(n^2)$ | $O(n)$ | $O(n^2)$ |
| 折半 | $O(n^2)$ | $O(n\log n)$ | $O(n^2)$ |
| 希尔 | 约 $O(n^{1.3})$ | — | $O(n^2)$ |
| 冒泡 | $O(n^2)$ | $O(n)$ | $O(n^2)$ |
| 快速 | $O(n\log n)$ | $O(n\log n)$ | $O(n^2)$ |
| 选择 | $O(n^2)$ | $O(n^2)$ | $O(n^2)$ |
| 堆 | $O(n\log n)$ | $O(n\log n)$ | $O(n\log n)$ |
| 归并 | $O(n\log n)$ | $O(n\log n)$ | $O(n\log n)$ |
| 基数 | $O(k(n+m))$ | 同左 | 同左 |

| 算法 | 空间 | 稳定 |
|:----:|:----:|:----:|
| 插入 | $O(1)$ | 稳定 |
| 折半 | $O(1)$ | 稳定 |
| 希尔 | $O(1)$ | 不稳定 |
| 冒泡 | $O(1)$ | 稳定 |
| 快速 | $O(\log n)\sim O(n)$ | 不稳定 |
| 选择 | $O(1)$ | 不稳定 |
| 堆 | $O(1)$ | 不稳定 |
| 归并 | $O(n)$ | 稳定 |
| 基数 | $O(n+m)$ | 稳定 |

**与初始状态的关系**：

- 越有序越快：插入、冒泡；希尔也会受益
- 越有序越慢：快速（每次划分极不平衡）
- 与初始状态无关：选择、堆、归并、基数

> 折半插入的比较次数恒为 $O(n\log n)$、与初始状态无关，但移动次数不变，故整体仍为 $O(n^2)$；正序时移动为 0，最好可达 $O(n\log n)$。

> 希尔排序的最好情况取决于增量序列，教材没有统一结论，因此表中不写具体最好值；平均 $O(n^{1.3})$ 也只是经验量级。

**稳定性口诀**：

> **★考点**：**插、冒、归、基** → 稳定（直接插入、折半插入、冒泡、归并、基数）；**希、快、选、堆** → 不稳定（希尔、快速、简单选择、堆）。

**每趟能否确定某个元素的最终位置**：

| 算法 | 每趟/每次划分的结论 |
| --- | --- |
| 冒泡 | 当前无序区的**最大值**沉到末尾，该位置最终确定 |
| 简单选择 | 当前无序区的**最小值**换到开头，该位置最终确定 |
| 快速排序 | **枢轴**落到最终位置，且左边全小、右边全大 |
| 堆排序 | **堆顶（最值）** 送到输出端，该位置最终确定 |
| 直接插入 / 折半插入 | 不保证；只是有序区扩大一位，元素后续仍可能移动 |
| 希尔排序 | 不保证；一趟只保证各子序列内部有序 |
| 归并排序 | 不保证；一趟只保证每个归并段内部有序 |
| 基数排序 | 不保证；$k$ 趟全做完才整体有序 |

**空间与原地性**：

- 原地排序（$O(1)$）：直接插入、折半插入、希尔、冒泡、简单选择、堆排序。
- 非原地：快速排序（递归栈，平均 $O(\log n)$、最坏 $O(n)$）、归并排序（$O(n)$）、基数排序（$O(n+m)$）。

**选择建议**：

- 记录数小、基本有序 → 直接插入或冒泡；要求稳定 → 直接插入、冒泡、归并、基数。
- 记录数大、要求平均快、不要求稳定、能接受递归开销 → 快速排序（避免输入基本有序，或改用随机/三点取中选枢轴）。
- 要求最坏也稳定在 $O(n\log n)$、且不在乎空间 → 归并排序；要求原地且不要求稳定 → 堆排序。
- 关键字取值范围有限且可分位（多关键字） → 基数排序，可做到线性时间。
- 若对稳定性有要求又只能用简单选择的思想，可把“交换”改写为“后移插入”实现稳定化。

**比较类算法的下界**：除基数排序外，其余算法都靠比较关键字定序。用**判定树**可以证明，这类算法最坏情况下的比较次数不可能低于 $\Omega(n\log n)$，即 $O(n\log n)$ 已是基于比较的排序所能达到的最好数量级。基数排序不比较关键字，因而不受此下界约束，可达到线性阶。

<figure class="cpd-figure not-content" id="wz-w5-fig-20">
  <svg viewBox="0 0 700 470" role="img" aria-labelledby="wz-w5-title-20">
    <title id="wz-w5-title-20">9 种内部排序算法全景对比矩阵与比较排序 Ω(n log n) 下界判定树</title>
    <text class="fig-title" x="24" y="22" font-size="12.5">内部排序算法全景对比矩阵与基于比较的排序下界 Ω(n log n) 判定树</text>
    <rect class="fig-box-subtle" x="24" y="36" width="652" height="25" rx="3"/>
    <rect class="fig-box" x="24" y="61" width="652" height="207"/>
    <g class="fig-divider">
      <line x1="24" y1="61" x2="676" y2="61"/>
      <line x1="24" y1="84" x2="676" y2="84"/>
      <line x1="24" y1="107" x2="676" y2="107"/>
      <line x1="24" y1="130" x2="676" y2="130"/>
      <line x1="24" y1="153" x2="676" y2="153"/>
      <line x1="24" y1="176" x2="676" y2="176"/>
      <line x1="24" y1="199" x2="676" y2="199"/>
      <line x1="24" y1="222" x2="676" y2="222"/>
      <line x1="24" y1="245" x2="676" y2="245"/>
      <line x1="104" y1="36" x2="104" y2="268"/>
      <line x1="194" y1="36" x2="194" y2="268"/>
      <line x1="284" y1="36" x2="284" y2="268"/>
      <line x1="374" y1="36" x2="374" y2="268"/>
      <line x1="476" y1="36" x2="476" y2="268"/>
      <line x1="544" y1="36" x2="544" y2="268"/>
    </g>
    <g class="fig-title" font-size="11" text-anchor="middle">
      <text x="64" y="53">算法</text><text x="149" y="53">平均时间</text><text x="239" y="53">最好时间</text>
      <text x="329" y="53">最坏时间</text><text x="425" y="53">辅助空间</text><text x="510" y="53">稳定性</text>
      <text x="610" y="53">原地与初态特征</text>
    </g>
    <g font-size="10.5" text-anchor="middle">
      <text class="fig-label" x="64" y="76">直接插入</text><text class="fig-muted" x="149" y="76">O(n²)</text><text class="fig-green" x="239" y="76">O(n)</text><text class="fig-red" x="329" y="76">O(n²)</text><text class="fig-blue" x="425" y="76">O(1)</text><text class="fig-green" x="510" y="76">稳定</text><text class="fig-muted" x="610" y="76">原地 · 越有序越快</text>
      <text class="fig-label" x="64" y="99">折半插入</text><text class="fig-muted" x="149" y="99">O(n²)</text><text class="fig-green" x="239" y="99">O(n log n)</text><text class="fig-red" x="329" y="99">O(n²)</text><text class="fig-blue" x="425" y="99">O(1)</text><text class="fig-green" x="510" y="99">稳定</text><text class="fig-muted" x="610" y="99">原地 · 比较无关初态</text>
      <text class="fig-label" x="64" y="122">希尔排序</text><text class="fig-blue" x="149" y="122">约 O(n^1.3)</text><text class="fig-muted" x="239" y="122">—</text><text class="fig-red" x="329" y="122">O(n²)</text><text class="fig-blue" x="425" y="122">O(1)</text><text class="fig-red" x="510" y="122">不稳定</text><text class="fig-muted" x="610" y="122">原地 · 依赖增量序列</text>
      <text class="fig-label" x="64" y="145">冒泡排序</text><text class="fig-muted" x="149" y="145">O(n²)</text><text class="fig-green" x="239" y="145">O(n)</text><text class="fig-red" x="329" y="145">O(n²)</text><text class="fig-blue" x="425" y="145">O(1)</text><text class="fig-green" x="510" y="145">稳定</text><text class="fig-muted" x="610" y="145">原地 · 越有序越快</text>
      <text class="fig-accent" x="64" y="168">快速排序</text><text class="fig-green" x="149" y="168">O(n log n)</text><text class="fig-green" x="239" y="168">O(n log n)</text><text class="fig-red" x="329" y="168">O(n²)</text><text class="fig-orange" x="425" y="168">O(log n)&#126;O(n)</text><text class="fig-red" x="510" y="168">不稳定</text><text class="fig-orange" x="610" y="168">非原地 · 越乱越好</text>
      <text class="fig-label" x="64" y="191">简单选择</text><text class="fig-muted" x="149" y="191">O(n²)</text><text class="fig-red" x="239" y="191">O(n²)</text><text class="fig-red" x="329" y="191">O(n²)</text><text class="fig-blue" x="425" y="191">O(1)</text><text class="fig-red" x="510" y="191">不稳定</text><text class="fig-muted" x="610" y="191">原地 · 与初态无关</text>
      <text class="fig-label" x="64" y="214">堆排序</text><text class="fig-green" x="149" y="214">O(n log n)</text><text class="fig-green" x="239" y="214">O(n log n)</text><text class="fig-green" x="329" y="214">O(n log n)</text><text class="fig-blue" x="425" y="214">O(1)</text><text class="fig-red" x="510" y="214">不稳定</text><text class="fig-muted" x="610" y="214">原地 · 与初态无关</text>
      <text class="fig-label" x="64" y="237">二路归并</text><text class="fig-green" x="149" y="237">O(n log n)</text><text class="fig-green" x="239" y="237">O(n log n)</text><text class="fig-green" x="329" y="237">O(n log n)</text><text class="fig-orange" x="425" y="237">O(n)</text><text class="fig-green" x="510" y="237">稳定</text><text class="fig-muted" x="610" y="237">非原地 · 与初态无关</text>
      <text class="fig-purple" x="64" y="260">基数排序</text><text class="fig-purple" x="149" y="260">O(k(n+m))</text><text class="fig-purple" x="239" y="260">O(k(n+m))</text><text class="fig-purple" x="329" y="260">O(k(n+m))</text><text class="fig-orange" x="425" y="260">O(n+m)</text><text class="fig-green" x="510" y="260">稳定</text><text class="fig-purple" x="610" y="260">非比较 · 线性阶</text>
    </g>
    <text class="fig-title" x="24" y="294" font-size="12">基于比较排序的下界证明（n = 3 判定树，叶数 = 3! = 6）</text>
    <g class="fig-line">
      <line x1="220" y1="326" x2="124" y2="358"/><line x1="220" y1="326" x2="316" y2="358"/>
      <line x1="124" y1="368" x2="66" y2="404"/><line x1="124" y1="368" x2="168" y2="400"/>
      <line x1="168" y1="410" x2="134" y2="440"/><line x1="168" y1="410" x2="198" y2="440"/>
      <line x1="316" y1="368" x2="264" y2="404"/><line x1="316" y1="368" x2="364" y2="400"/>
      <line x1="364" y1="410" x2="330" y2="440"/><line x1="364" y1="410" x2="392" y2="440"/>
    </g>
    <g font-size="9.5" text-anchor="middle">
      <rect class="fig-box" x="158" y="334" width="18" height="14" rx="3"/><text class="fig-green" x="167" y="344">是</text>
      <rect class="fig-box" x="264" y="334" width="18" height="14" rx="3"/><text class="fig-red" x="273" y="344">否</text>
      <rect class="fig-box" x="82" y="378" width="18" height="14" rx="3"/><text class="fig-green" x="91" y="388">是</text>
      <rect class="fig-box" x="144" y="376" width="18" height="14" rx="3"/><text class="fig-red" x="153" y="386">否</text>
      <rect class="fig-box" x="276" y="378" width="18" height="14" rx="3"/><text class="fig-green" x="285" y="388">是</text>
      <rect class="fig-box" x="338" y="376" width="18" height="14" rx="3"/><text class="fig-red" x="347" y="386">否</text>
    </g>
    <g font-size="10.5" text-anchor="middle">
      <rect class="fig-box-accent" x="190" y="305" width="60" height="22" rx="4"/><text class="fig-accent" x="220" y="320">a &lt; b ?</text>
      <rect class="fig-box-blue" x="96" y="348" width="56" height="22" rx="4"/><text class="fig-blue" x="124" y="363">b &lt; c ?</text>
      <rect class="fig-box-blue" x="288" y="348" width="56" height="22" rx="4"/><text class="fig-blue" x="316" y="363">a &lt; c ?</text>
      <rect class="fig-box-green" x="40" y="394" width="52" height="20" rx="4"/><text class="fig-green" x="66" y="408">(a,b,c)</text>
      <rect class="fig-box-blue" x="142" y="390" width="52" height="20" rx="4"/><text class="fig-blue" x="168" y="404">a &lt; c ?</text>
      <rect class="fig-box-green" x="108" y="430" width="52" height="20" rx="4"/><text class="fig-green" x="134" y="444">(a,c,b)</text>
      <rect class="fig-box-green" x="172" y="430" width="52" height="20" rx="4"/><text class="fig-green" x="198" y="444">(c,a,b)</text>
      <rect class="fig-box-green" x="238" y="394" width="52" height="20" rx="4"/><text class="fig-green" x="264" y="408">(b,a,c)</text>
      <rect class="fig-box-blue" x="338" y="390" width="52" height="20" rx="4"/><text class="fig-blue" x="364" y="404">b &lt; c ?</text>
      <rect class="fig-box-green" x="304" y="430" width="52" height="20" rx="4"/><text class="fig-green" x="330" y="444">(b,c,a)</text>
      <rect class="fig-box-green" x="366" y="430" width="52" height="20" rx="4"/><text class="fig-green" x="392" y="444">(c,b,a)</text>
    </g>
    <rect class="fig-box-subtle" x="432" y="296" width="244" height="156" rx="6"/>
    <text class="fig-accent" x="446" y="316" font-size="11.5">下界推导（信息论边界）</text>
    <g font-size="10.8">
      <text class="fig-muted" x="446" y="338">① n 个不同关键字共有 n! 种排列</text>
      <text class="fig-muted" x="446" y="358">② 每次二元比较分出 2 条分支</text>
      <text class="fig-muted" x="446" y="378">③ 树高 h 最多包含 2ʰ 个叶结点：</text>
      <text class="fig-blue" x="454" y="398">2ʰ ≥ n!  ⇒  h ≥ ⌈log₂(n!)⌉</text>
      <text class="fig-green" x="446" y="418">④ Stirling 近似：h = Ω(n log n)</text>
      <text class="fig-purple" x="446" y="440">★ 基数排序不比较关键字 → 破下界</text>
    </g>
  </svg>
  <figcaption>排序方法全景矩阵与比较排序下界判定树：稳定性口诀“插冒归基稳，希快选堆不稳”，比较排序最坏至少 Ω(n log n)</figcaption>
</figure>