一、链表定义
使用任意的存储单元(可以连续也可以不连续)来存储相同类型数据。线性表,链式存储。
- 单链表
存储数据的单元-链节点既要存储数据元素的值,又有存放其直接后继元素所在链节点地址(即后继指针)的链表 - 双链表
每个链节点中有两个指针,分别指向直接后继和直接前驱 - 循环链表
最后一个链节点指向头节点,形成环
二、算法复杂度
访问(Access)-O(N)
搜索(Search)-O(N)
插入(Insert)-O(1)
删除(Delete)-O(1)
三、常用操作
创建链表
// 单链表的定义
struct ListNode {
int val; // 节点上存储的元素
ListNode *next; // 指向下一个节点的指针
ListNode(int x) : val(x), next(NULL) {} // 节点的构造函数
};
//创建与初始化节点
ListNode* head = new ListNode(5);
//另一种初始化方式
ListNode* head = new ListNode();
head->val = 5;
添加元素
void insert(int index, int data) {
if (index < 0 || index > size) {
return;
}
ListNode *newNode = new ListNode(data);
if (index == 0) {
// 插入到链表头部
newNode->next = head->next;
head->next = newNode;
} else {
// 找到index-1位置的节点
ListNode *current = head;
for (int i = 0; i < index - 1; ++i) {
if (current->next == nullptr) {
delete newNode;
return;
}
current = current->next;
}
// 插入新节点
newNode->next = current->next;
current->next = newNode;
}
size++; // 更新链表大小
}
删除元素
ListNode* removeElements(ListNode* head, int val) {
ListNode* dummyHead = new ListNode(0); // 设置一个虚拟头结点
dummyHead->next = head; // 将虚拟头结点指向head,这样方便后面做删除操作
ListNode* cur = dummyHead;
while (cur->next != NULL) {
if(cur->next->val == val) {
ListNode* tmp = cur->next;
cur->next = cur->next->next;
delete tmp;
} else {
cur = cur->next;
}
}
head = dummyHead->next;
delete dummyHead;
return head;
}
//清空链表
void clear(ListNode *head) {
ListNode *current = head;
while (current != nullptr) {
ListNode *temp = current;
current = current->next;
delete temp;
}
head = nullptr; // 重置头节点为nullptr,表示链表为空
}
查找元素
// 查找链表中值为data的节点
ListNode* find(ListNode *head,int data) {
ListNode *current = head;
while (current != nullptr) {
if (current->value == data) {
return current; // 找到匹配的节点,返回指针
}
current = current->next;
}
return nullptr; // 未找到匹配的节点,返回nullptr
}
访问元素
// 获取链表索引index位置的元素值
int get(ListNode *head,int index) {
if (index < 0) {
return std::numeric_limits<int>::min(); // 返回最小整数值,表示索引无效
}
ListNode *current = head;
int currentIndex = 0;
while (current != nullptr) {
if (currentIndex == index) {
return current->value; // 找到索引位置,返回值
}
currentIndex++;
current = current->next;
}
return std::numeric_limits<int>::min(); // 索引超出链表范围,返回最小整数值
}
遍历并打印链表
// 打印链表
void printList(ListNode *current) {
while (current != nullptr) {
std::cout << current->value << " ";
current = current->next;
}
std::cout << std::endl;}
链表长度
int length(ListNode *current) {
int count = 0;
while (current != nullptr) {
count++;
current = current->next;
}
return count;
}