-
首先,链表由节点组成,每个节点应该包含数据和指向下一个节点的指针。
-
结构体可以包含数据域和指针域。
-
比如,假设链表存储整数,那节点的结构体应该有一个int类型的数据和一个指向同样结构体的指针。结构体定义大概是这样的:
struct Node {
int data;
struct Node* next;
};
-
代码示例:
#include <stdio.h> #include <stdlib.h>// 定义链表节点结构 struct Node {int data;struct Node* next; };// 在链表头部插入新节点 void insertAtHead(struct Node** head_ref, int data) {struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));new_node->data = data;new_node->next = *head_ref;*head_ref = new_node; }// 删除指定值的节点 void deleteNode(struct Node** head_ref, int key) {struct Node *temp = *head_ref, *prev = NULL;// 处理头节点为删除目标的情况if (temp != NULL && temp->data == key) {*head_ref = temp->next;free(temp);return;}// 遍历查找目标节点while (temp != NULL && temp->data != key) {prev = temp;temp = temp->next;}// 未找到目标节点if (temp == NULL) return;// 删除节点并调整指针prev->next = temp->next;free(temp); }// 遍历并打印链表 void printList(struct Node* node) {while (node != NULL) {printf("%d -> ", node->data);node = node->next;}printf("NULL\n"); }// 释放链表内存 void freeList(struct Node* head) {struct Node* tmp;while (head != NULL) {tmp = head;head = head->next;free(tmp);} }int main() {struct Node* head = NULL;// 插入测试insertAtHead(&head, 3);insertAtHead(&head, 2);insertAtHead(&head, 1);printf("初始链表: ");printList(head); // 输出: 1 -> 2 -> 3 -> NULL// 删除测试deleteNode(&head, 2);printf("删除2后的链表: ");printList(head); // 输出: 1 -> 3 -> NULLdeleteNode(&head, 1);printf("删除1后的链表: ");printList(head); // 输出: 3 -> NULLdeleteNode(&head, 3);printf("删除3后的链表: ");printList(head); // 输出: NULL// 释放内存freeList(head);return 0; }
5.输出结果:
初始链表: 1 -> 2 -> 3 -> NULL 删除2后的链表: 1 -> 3 -> NULL 删除1后的链表: 3 -> NULL 删除3后的链表: NULL
6.代码解释:
-
节点结构 (
struct Node
):-
data
:存储节点值(此处为整型) -
next
:指向下一个节点的指针
-
-
核心操作:
-
insertAtHead
:在链表头部插入新节点-
时间复杂度:O(1)
-
使用二级指针修改头节点指针
-
-
deleteNode
:删除指定值的节点-
时间复杂度:O(n)
-
处理头节点删除和中间节点删除两种情况
-
-
printList
:遍历并打印链表 -
freeList
:释放链表内存,避免内存泄漏
-
-
执行流程:
-
初始化空链表
-
依次插入3个节点(1→2→3)
-
分步删除节点并打印结果
-
最终释放所有内存
-