链表基本操作

(临时抱佛脚的笔记)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#include <stdio.h>
#include <stdlib.h>

// 定义链表节点结构
struct Node {
int data;
struct Node *next;
};

// 创建新节点
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("内存分配失败\n");
exit(1);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}

// 在链表头部插入节点
struct Node* insertAtBeginning(struct Node *head, int data) {
struct Node *newNode = createNode(data);
newNode->next = head;
return newNode;
}

// 在链表尾部插入节点
void insertAtEnd(struct Node *head, int data) {
struct Node *newNode = createNode(data);
struct Node *temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}

// 删除第一个值为 data 的节点
struct Node* deleteNode(struct Node *head, int data) {
struct Node *current = head;
struct Node *prev = NULL;

// 查找要删除的节点并记录其前一个节点
while (current != NULL && current->data != data) {
prev = current;
current = current->next;
}

// 若找到要删除的节点,则删除它
if (current != NULL) {
if (prev == NULL) {
head = current->next; // 删除头节点
} else {
prev->next = current->next; // 删除中间或尾节点
}
free(current);
}

return head;
}

// 打印链表
void printList(struct Node *head) {
struct Node *temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}

// 释放链表节点
void freeList(struct Node *head) {
struct Node *temp;
while (head != NULL) {
temp = head;
head = head->next;
free(temp);
}
}

int main() {
struct Node *head = NULL; // 初始化链表头节点

// 在链表头部插入节点
head = insertAtBeginning(head, 10);
head = insertAtBeginning(head, 20);
head = insertAtBeginning(head, 30);

// 在链表尾部插入节点
insertAtEnd(head, 40);
insertAtEnd(head, 50);

printf("链表内容:\n");
printList(head);

// 删除节点
head = deleteNode(head, 20);

printf("删除后的链表内容:\n");
printList(head);

// 释放链表节点内存
freeList(head);

return 0;
}