返回
从零解析链表:增删查改,样样精通!
后端
2024-01-12 01:17:00
在计算机科学的世界里,链表是一种基本且重要的数据结构,广泛应用于各种场景。本篇文章将带你从头到尾认识链表,揭秘它的定义、实现方式以及常见的增删查改操作。
链表的定义
链表是一种非连续存储的数据结构,其元素(称为节点)通过指针连接在一起。与顺序表中数据连续存储的方式不同,链表中的节点可以分散在内存中的不同位置。
单链表的实现
单链表是最简单的链表类型,每个节点包含两个字段:数据和指向下一个节点的指针。以下是单链表节点的C++实现:
struct Node {
int data;
Node* next;
};
增删查改操作
- 插入: 在链表中插入一个新节点,需要修改前后节点的指针。
- 删除: 从链表中删除一个节点,需要修改前后节点的指针。
- 查找: 通过遍历链表,找到包含特定数据的节点。
- 修改: 找到特定节点后,修改其数据字段。
示例代码
以下代码展示了单链表的增删查改操作:
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
};
Node* head = NULL; // 头节点
// 插入节点
void insertNode(int data) {
Node* newNode = new Node;
newNode->data = data;
newNode->next = head;
head = newNode;
}
// 删除节点
void deleteNode(int data) {
if (head == NULL) {
cout << "链表为空" << endl;
return;
}
Node* curr = head;
Node* prev = NULL;
while (curr != NULL && curr->data != data) {
prev = curr;
curr = curr->next;
}
if (curr == NULL) {
cout << "找不到要删除的节点" << endl;
return;
}
if (prev == NULL) {
head = head->next;
} else {
prev->next = curr->next;
}
delete curr;
}
// 查找节点
Node* findNode(int data) {
Node* curr = head;
while (curr != NULL && curr->data != data) {
curr = curr->next;
}
return curr;
}
// 修改节点
void modifyNode(int oldData, int newData) {
Node* node = findNode(oldData);
if (node == NULL) {
cout << "找不到要修改的节点" << endl;
return;
}
node->data = newData;
}
int main() {
insertNode(10);
insertNode(20);
insertNode(30);
cout << "链表中的数据:" << endl;
Node* curr = head;
while (curr != NULL) {
cout << curr->data << " ";
curr = curr->next;
}
cout << endl;
deleteNode(20);
cout << "删除节点 20 后,链表中的数据:" << endl;
curr = head;
while (curr != NULL) {
cout << curr->data << " ";
curr = curr->next;
}
cout << endl;
Node* node = findNode(30);
if (node != NULL) {
cout << "找到节点 30,其数据为:" << node->data << endl;
}
modifyNode(10, 40);
cout << "修改节点 10 后,链表中的数据:" << endl;
curr = head;
while (curr != NULL) {
cout << curr->data << " ";
curr = curr->next;
}
cout << endl;
return 0;
}
总结
链表是一种广泛使用的线性表数据结构,其独特的非连续存储方式使其具有在需要动态添加或删除元素时高效操作的优点。理解链表的定义、实现方式以及常见的增删查改操作对于掌握数据结构至关重要。