1. 学习目标
- 理解顺序表在连续地址区间内存储元素,并能用基地址计算下标位置。
- 先能独立写出定长顺序表的查找、插入、删除,再理解动态扩容与拷贝。
- 严谨推导顺序表插入、删除操作的平均移动元素次数与时间复杂度。
- 能解释连续存储为何通常有利于顺序遍历时的缓存局部性。
2. 顺序表的物理存储原理
顺序表(Sequential List)把线性表元素依次放在一段连续地址区间内。这里的“连续”指程序看到的地址连续,不要求底层物理内存页也连续。
寻址数学公式
若每个元素占据
该物理特性保证了顺序表定位任意元素的时间独立于表长
3. 顺序表 ADT 抽象规约
ADT SeqList<T>
数据对象:同类型数据元素构成的有限序列 {a0, a1, ..., an-1}
核心操作:
create(capacity) 初始化指定容量的空表
size() 返回当前有效元素个数
capacity() 返回当前物理最大容量
get(index) 获取指定下标元素引用(带边界检查)
push_back(value) 尾部追加元素(容量不足自动扩容)
insert(index, value) 在指定下标插入元素,后续元素后移
erase(index) 删除指定下标元素,后续元素前移
find(value) 查找目标值首次出现的下标
clear() 清空表内元素
4. 先学基本算法:定长顺序表
本节统一用 0 起始下标:长度为 n 时,有效元素位于 [0, n);插入位置可以是 [0, n],删除位置只能是 [0, n)。size 是已有元素个数,capacity 是数组最多能容纳的元素个数,二者不能混用。
例如 A = [10, 20, 30, 40],size = 4,容量为 8。要在下标 1 插入 15,先把 40、30、20 从右向左各移一格,再写入 15:
原表: 10 20 30 40 _ _ _ _
移动后: 10 20 20 30 40 _ _ _
写入后: 10 15 20 30 40 _ _ _
下标: 0 1 2 3 4
下面是可以直接编译运行的最小实现。get 和 erase 用输出参数返回元素,bool 表示操作是否成功;查找失败返回 -1。
#include <cassert>
#include <iostream>
struct SeqListInt {
static constexpr int capacity = 8;
int data[capacity]{};
int size = 0;
bool get(int index, int& value) const {
if (index < 0 || index >= size) return false;
value = data[index];
return true;
}
int find(int value) const {
for (int i = 0; i < size; ++i)
if (data[i] == value) return i;
return -1;
}
bool insert(int index, int value) {
if (index < 0 || index > size || size == capacity) return false;
for (int i = size; i > index; --i)
data[i] = data[i - 1]; // 右移,必须从后往前
data[index] = value;
++size;
return true;
}
bool erase(int index, int& removed) {
if (index < 0 || index >= size) return false;
removed = data[index];
for (int i = index; i < size - 1; ++i)
data[i] = data[i + 1]; // 左移,必须从前往后
--size;
return true;
}
};
int main() {
SeqListInt list;
assert(list.insert(0, 10));
assert(list.insert(1, 20));
assert(list.insert(2, 30));
assert(list.insert(1, 15)); // [10, 15, 20, 30]
assert(list.find(20) == 2);
int value = 0;
assert(list.get(1, value) && value == 15);
assert(list.erase(2, value) && value == 20); // [10, 15, 30]
assert(list.size == 3 && list.data[2] == 30);
for (int i = 0; i < list.size; ++i) std::cout << list.data[i] << ' ';
}
编译:c++ -std=c++17 -Wall -Wextra -pedantic seq_list.cpp -o seq_list && ./seq_list。预期输出:10 15 30。自己再测:空表删除、满表插入、表头插入、表尾插入、表头删除、表尾删除。
写循环时先算移动范围
插入到 index:移动原下标 index ... size-1,共 size-index 个。删除 index:移动原下标 index+1 ... size-1,共 size-index-1 个。
5. 进阶示例:动态顺序表
下面的类用于理解扩容与深拷贝,假定 T 可默认构造、可拷贝赋值。真实项目通常直接使用 std::vector<T>;完整的通用容器还要处理元素构造、异常安全、整数溢出等问题。
#include <iostream>
#include <stdexcept>
#include <algorithm>
#include <memory>
template <typename T>
class SeqList {
private:
T* data; // 指向堆内存连续数组的指针
int length; // 当前有效元素个数 (size)
int maxCapacity; // 物理最大容量 (capacity)
void expand() {
int newCapacity = (maxCapacity == 0) ? 4 : maxCapacity * 2;
std::unique_ptr<T[]> newData(new T[newCapacity]);
for (int i = 0; i < length; ++i) {
newData[i] = data[i];
}
delete[] data;
data = newData.release();
maxCapacity = newCapacity;
}
public:
explicit SeqList(int initCapacity = 10)
: data(initCapacity > 0 ? new T[initCapacity] : nullptr),
length(0),
maxCapacity(initCapacity > 0 ? initCapacity : 0) {}
~SeqList() {
delete[] data;
}
// 禁用默认浅拷贝,实现安全深拷贝
SeqList(const SeqList& other)
: data(nullptr), length(0), maxCapacity(0) {
std::unique_ptr<T[]> copy(
other.maxCapacity > 0 ? new T[other.maxCapacity] : nullptr);
for (int i = 0; i < other.length; ++i) copy[i] = other.data[i];
data = copy.release();
length = other.length;
maxCapacity = other.maxCapacity;
}
SeqList& operator=(const SeqList& other) {
if (this != &other) {
std::unique_ptr<T[]> newData(
other.maxCapacity > 0 ? new T[other.maxCapacity] : nullptr);
for (int i = 0; i < other.length; ++i) newData[i] = other.data[i];
delete[] data;
data = newData.release();
length = other.length;
maxCapacity = other.maxCapacity;
}
return *this;
}
int size() const { return length; }
int capacity() const { return maxCapacity; }
bool empty() const { return length == 0; }
void clear() { length = 0; }
T& at(int index) {
if (index < 0 || index >= length) {
throw std::out_of_range("SeqList::at index out of range");
}
return data[index];
}
const T& at(int index) const {
if (index < 0 || index >= length) {
throw std::out_of_range("SeqList::at index out of range");
}
return data[index];
}
T& operator[](int index) { return data[index]; }
const T& operator[](int index) const { return data[index]; }
void push_back(const T& value) {
T saved = value; // value 可能引用本表元素;扩容前先保存
if (length >= maxCapacity) expand();
data[length] = saved;
++length;
}
void insert(int index, const T& value) {
if (index < 0 || index > length) {
throw std::out_of_range("SeqList::insert index invalid");
}
T saved = value; // 避免扩容或移位令 value 失效或改变
if (length >= maxCapacity) expand();
// 从后向前移动元素,避免数据覆盖
for (int i = length; i > index; --i) {
data[i] = data[i - 1];
}
data[index] = saved;
++length;
}
void erase(int index) {
if (index < 0 || index >= length) {
throw std::out_of_range("SeqList::erase index invalid");
}
// 从前向后移动元素覆盖
for (int i = index; i < length - 1; ++i) {
data[i] = data[i + 1];
}
--length;
}
int find(const T& value) const {
for (int i = 0; i < length; ++i) {
if (data[i] == value) return i;
}
return -1;
}
};
6. 核心算法复杂度与平均移动次数推导
1. 插入操作移动次数推导
设在长度为
2. 删除操作移动次数推导
设删除第
3. 操作综合性能表
| 操作类型 | 最好时间复杂度 | 平均时间复杂度 | 最坏时间复杂度 | 额外空间复杂度 | 性能本质分析 |
|---|---|---|---|---|---|
| 下标直接访问 | 基地址加偏移量寻址 | ||||
| 尾部追加 (push_back) | 摊销 |
扩容当次 |
容量不足时重新分配并复制 | ||
| 任意位置插入 | 扩容当次 |
后续元素后移,扩容还要复制 | |||
| 任意位置删除 | 受制于后续元素前移成本 | ||||
| 无序线性查找 | 逐个比对键值 |
上表的空间复杂度按动态顺序表单次操作计算;若表已有足够容量,插入、删除只需 push_back 的摊销
7. 常见易错点
移动方向颠倒
在执行 insert 时,循环必须从后向前(for (int i = length; i > index; --i));若从前向后移动,会导致前一个元素覆盖后一个元素,造成全量数据丢失。同理,erase 必须从前向后移动覆盖。
析构双重释放 (Double Free)
顺序表类内部维护堆指针,若未自定义拷贝构造函数与赋值重载函数,C++ 默认执行浅拷贝(逐位复制指针),导致多个对象析构时对同一物理地址执行多次 delete[],引发运行时内存崩溃。
下标与边界
长度为 n 时,读取/删除的合法下标为 0 到 n-1;插入允许 n,即在末尾追加。空表可以在 0 插入,但不能读取或删除。
动态示例的适用范围
new T[capacity] 会默认构造整个容量内的对象,因此上面的模板类只适合作为课堂示例。若 T 的赋值会抛异常,插入和删除还需要更完整的异常安全设计;不要把它当成 std::vector 的替代品。
8. 练习题与自测
- 从顺序表中删除所有值为
的元素,要求时间复杂度为 ,额外空间复杂度为 。 - 试编写算法将顺序表中的元素就地逆置(In-place Reverse)。
- 表长为 5、容量为 5 时,在下标 2 插入为何失败?扩容后需要移动几个原表元素?
- 表
[3, 5, 7, 9]在下标 1 删除后是什么?循环中的i应从几开始,到几结束?
练习 1 参考实现(双指针快慢扫描)
void removeAllX(SeqListInt& list, int x) {
int write = 0; // [0, write) 始终是已经保留的元素
for (int read = 0; read < list.size; ++read)
if (list.data[read] != x)
list.data[write++] = list.data[read];
list.size = write; // 后面的旧数据不再属于有效元素
}
练习 2 参考实现
void reverse(SeqListInt& list) {
for (int left = 0, right = list.size - 1; left < right; ++left, --right)
std::swap(list.data[left], list.data[right]);
}
练习 3、4 答案
- 容量已满;扩容后,原下标 2、3、4 三个元素需要右移,另有扩容时复制原表元素的成本。
- 得到
[3, 7, 9];i从 1 开始,最后一次为 2(把原下标 3 的元素移到 2)。
9. 从课本算法过渡到 std::vector
std::vector<int> 是 C++ 中常用的动态连续存储容器。用 size() 看有效元素个数,用 capacity() 看已分配容量;reserve() 只增加可用容量,不改变有效元素个数。insert 和 erase 使用迭代器位置:
#include <vector>
std::vector<int> a{10, 20, 30};
a.insert(a.begin() + 1, 15); // [10, 15, 20, 30]
a.erase(a.begin() + 2); // [10, 15, 30]
课堂上先手写数组移位算法,写应用代码时再用 std::vector。扩容会使原有指针、引用和迭代器失效;即使没有扩容,插入/删除位置及其后的迭代器或引用也可能失效。
10. 推荐教程与学习顺序
- 先读本页第 2~4 节:自己拿纸模拟表头、表中、表尾插入/删除,暂时跳过动态模板类。
- 看 OpenDSA:Array-Based List Implementation:有插入与删除的移位演示和练习(英文)。
- 做本页第 8 节练习:不看答案写出边界判断、循环方向与移动次数。
- 最后看 Microsoft Learn:C++
vector类:对应查size、capacity、insert、erase、reserve,并回看本页第 5、6、9 节。
11. 本课检查清单
- [ ] 我能准确写出顺序表元素物理地址计算公式。
- [ ] 我能推导出顺序表插入与删除的平均移动元素次数(
与 )。 - [ ] 我能手写定长顺序表的查找、插入和删除,并处理空表/满表。
- [ ] 我能解释动态扩容与
size、capacity的区别。 - [ ] 我能解释为什么顺序遍历顺序表通常具有较好的缓存局部性。
上一节:上一节
下一节:下一节
代码索引:代码索引