C++ 中 List 的介绍与常用操作的模拟实现
在 C++ 中,std::list
是一个双向链表(doubly linked list)实现的容器,它属于标准模板库(STL)的一部分。与 std::vector
不同,std::list
允许在常数时间内插入或删除元素(只要位置是已知的),而代价是它不支持随机访问。下面是 C++ 中 std::list
的一些常用操作和其模拟实现。
std::list
的基本特性
- 双向链表:每个节点都知道其前一个和后一个节点。
- 动态大小:能够高效地插入和删除元素。
- 双向迭代:支持正向和反向遍历。
常用操作
下面是一些 std::list
的常用操作:
定义和初始化:
std::list<int> myList; // 空链表
std::list<int> myList(5, 10); // 长度为5,所有元素都是10
std::list<int> anotherList = {1, 2, 3}; // 使用初始化列表
插入元素:
myList.push_back(20); // 在末尾插入
myList.push_front(5); // 在头部插入
// 在某个位置插入
auto it = myList.begin();
std::advance(it, 2); // 移动迭代器到第三个元素
myList.insert(it, 15); // 在此位置插入15
删除元素:
myList.pop_back(); // 删除末尾元素
myList.pop_front(); // 删除头部元素
// 删除特定位置的元素
auto it = myList.begin();
std::advance(it, 1); // 移动到第二个元素
myList.erase(it);
// 删除特定值的所有元素
myList.remove(10);
访问元素:
int first = myList.front(); // 访问第一个元素
int last = myList.back(); // 访问最后一个元素
遍历:
for (int value : myList) {
std::cout << value << " ";
}
// 使用迭代器
for (auto it = myList.begin(); it != myList.end(); ++it) {
std::cout << *it << " ";
}
其它操作:
myList.clear(); // 清空列表
myList.reverse(); // 反转列表
myList.sort(); // 排序列表
myList.unique(); // 去除连续相等的元素
myList.merge(anotherList); // 合并另一个已排序的列表
模拟实现的简单示例
虽然 C++ 提供了标准的 std::list
实现,但你可以从头模拟一个简单的链表来更好地理解它的工作原理。
#include <iostream>
// 节点结构
struct Node {
int data;
Node* next;
Node* prev;
Node(int value) : data(value), next(nullptr), prev(nullptr) {}
};
// 双向链表类
class DoublyLinkedList {
public:
DoublyLinkedList() : head(nullptr), tail(nullptr) {}
// 添加到尾部
void push_back(int value) {
Node* newNode = new Node(value);
if (!tail) {
head = tail = newNode;
} else {
tail->next = newNode;
newNode->prev = tail;
tail = newNode;
}
}
// 打印链表
void print() {
Node* current = head;
while (current) {
std::cout << current->data << " ";
current = current->next;
}
std::cout << std::endl;
}
// 删除链表中的所有节点
void clear() {
Node* current = head;
while (current) {
Node* next = current->next;
delete current;
current = next;
}
head = tail = nullptr;
}
~DoublyLinkedList() {
clear();
}
private:
Node* head;
Node* tail;
};
int main() {
DoublyLinkedList list;
list.push_back(1);
list.push_back(2);
list.push_back(3);
std::cout << "List contents: ";
list.print();
list.clear();
return 0;
}
这段代码展示了一个简单的双向链表的数据结构及其基本操作。通过这种方式,你可以深入理解 std::list
在底层是如何运作的。