本篇博客主要讲解了链表的各项基本操作。
一、链表的初始化
1.链表的概念
链表是一种物理存储上非连续,数据元素的逻辑顺序通过链表中的指针链接次序,实现的一种线性存储结构。
链表由一系列节点(链表中每一个元素称为节点)组成,节点在运行时动态生成 (malloc),每个节点包括两个部分:
一个是存储数据元素的数据域
另一个是存储下一个节点地址的指针域
typedef struct Node {
int data;
struct Node* next;
} Node;
2.创建链表
首先创建一个节点,并且这个节点包含下一节点的地址,而下一节点又包含下下节点的地址,以此类推。
Node* createList(int arr[], int n) {
Node* head = NULL;
Node* tail = NULL;
for (int i = 0; i < n; ++i) {
Node* newNode = (Node*) malloc(sizeof(Node));
newNode->data = arr[i];
newNode->next = NULL;
if (head == NULL) {
head = newNode;
tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
return head;
}
二、链表操作
1.增加节点
将链表末尾的空指针置为新节点的地址,并将新节点的指针域置空。
输入首节点,节点数,和新data。
Node* insert(Node* head, int position, int value) {
Node* newNode = (Node*)malloc(sizeof(Node))