跳转到内容
新建笔记

C++ 单向链表:节点所有权、索引与异常安全

单向链表的节点包含一个元素和指向后继的指针。它适合学习“先找到连接位置,再改指针”的过程;一般业务代码应先考虑 std::vector 或 std::forward_list 等标准容器。这里保留原笔记的索引式 insert/append/remove/find/get/length/clear/print 接口,补齐所有权、边界和异常说明。

原来在 10 → 20 → 30 的索引 1 插入 15,分两步理解:新节点的 next 保存旧的 20 节点;前驱 10 的 next 再改为新节点。两处 next 属于不同对象。

插入前:head → [10 | next] → [20 | next] → [30 | null]
新节点: [15 | next] ───┘
插入后:head → [10 | next] → [15 | next] → [20 | next] → [30 | null]

链表始终保持两个不变量:size_ 等于可达节点数;最后一个节点指向 nullptr,空表的 head_ 为 nullptr。节点由链表独占,所以不能让默认浅复制生成两个会释放同一批节点的链表。

此教学实现使用原来的 int 索引,以保留负数越界检查;当长度达到 int 最大值时拒绝继续插入。节点隐藏在类内,调用者通过元素接口访问。禁止复制和移动,避免把节点所有权处理留给隐式生成的成员函数。

#include <iostream>
#include <limits>
#include <stdexcept>
#include <type_traits>
template <typename T>
class LinkedList {
static_assert(std::is_nothrow_destructible_v<T>,
"LinkedList requires a non-throwing element destructor");
struct Node {
T data;
Node* next;
Node(const T& value, Node* nextNode = nullptr)
: data(value), next(nextNode) {}
};
Node* head_ = nullptr;
int size_ = 0;
Node* nodeAt(int index) const {
if (index < 0 || index >= size_) throw std::out_of_range("index");
Node* current = head_;
for (int i = 0; i < index; ++i) current = current->next;
return current;
}
public:
LinkedList() = default;
~LinkedList() { clear(); }
LinkedList(const LinkedList&) = delete;
LinkedList& operator=(const LinkedList&) = delete;
LinkedList(LinkedList&&) = delete;
LinkedList& operator=(LinkedList&&) = delete;
void insert(int index, const T& value) {
if (index < 0 || index > size_) throw std::out_of_range("insert index");
if (size_ == std::numeric_limits<int>::max()) throw std::length_error("length");
if (index == 0) {
head_ = new Node(value, head_);
} else {
Node* previous = nodeAt(index - 1);
previous->next = new Node(value, previous->next);
}
++size_;
}
void append(const T& value) { insert(size_, value); }
void remove(int index) {
if (index < 0 || index >= size_) throw std::out_of_range("remove index");
Node* removed;
if (index == 0) {
removed = head_;
head_ = head_->next;
} else {
Node* previous = nodeAt(index - 1);
removed = previous->next;
previous->next = removed->next;
}
delete removed;
--size_;
}
int find(const T& value) const {
const Node* current = head_;
int index = 0;
while (current) {
if (current->data == value) return index;
current = current->next;
++index;
}
return -1;
}
T& get(int index) { return nodeAt(index)->data; }
const T& get(int index) const { return nodeAt(index)->data; }
int length() const noexcept { return size_; }
void clear() noexcept {
while (head_) {
Node* removed = head_;
head_ = head_->next;
delete removed;
}
size_ = 0;
}
void print(std::ostream& output = std::cout) const {
const Node* current = head_;
while (current) {
output << current->data;
current = current->next;
if (current) output << ' ';
}
output << '\n';
}
};
int main() {
LinkedList<int> list;
list.append(10);
list.append(20);
list.append(30);
list.insert(1, 15);
std::cout << "After insert: "; list.print();
list.remove(2);
std::cout << "After remove: "; list.print();
std::cout << "Index of 15: " << list.find(15) << '\n';
std::cout << "Element at index 2: " << list.get(2) << '\n';
std::cout << "Length of list: " << list.length() << '\n';
list.clear();
std::cout << "After clear: "; list.print();
return 0;
}

输出保留原例的操作顺序:

After insert: 10 15 20 30
After remove: 10 15 30
Index of 15: 1
Element at index 2: 30
Length of list: 3
After clear:

new Node(...) 成功构造后才把新地址写回连接位置,最后增加长度。如果内存分配或 T 的复制构造抛异常,链表原连接与长度保持不变,失败的新表达式负责释放已分配的节点存储。这里依赖元素复制操作不反过来修改链表等通常的值类型约定。new 表达式异常处理

删除先保存待删节点,再接回后继,最后销毁节点。clear() 使用迭代释放,不递归遍历长链;类的静态检查要求元素析构不抛异常。find 还需要元素支持相等比较,print 需要支持输出到流,调用这些成员时才需要相应能力。

操作有效范围或返回值最坏时间复杂度
insert(index, value)0 <= index <= length()O(n);头插 O(1)
append(value)在尾部插入;本实现没有尾指针O(n)
remove(index)0 <= index < length()O(n);头删 O(1)
get(index)同删除范围;返回元素引用O(n)
find(value)首个匹配索引;未找到为 -1O(n)
length()当前节点数O(1)
clear()、print()处理全部节点O(n),另计元素析构或输出成本

反复 append 建立 n 个节点需要 O(n²) 次节点遍历;维护尾指针或使用合适的标准容器可以改变这个代价。复杂度不是“链表所有插入都是 O(1)”:只有已经取得连接位置时,改指针本身才是常数步。

get 的引用在对应节点仍存在时有效。插入或删除其他节点不会移动该节点,但删除该元素、clear 或链表析构后,原引用会悬空;不能继续使用。此实现没有内部锁,同一链表上的并发读写需要外部同步。

验证时除了原来的 10/15/20/30 输出,还应检查空表删除、负索引、尾边界、重复值查找、连续清空,以及元素复制抛异常后原表未变化。链表测试应调用这一份实现,而不是在测试里重新写一套链表算法。

来源:CSDN 原文,首次发布于 2025-04-16。