带头结点的单链表插入与删除操作实现c代码
时间: 2024-10-14 14:15:27 浏览: 77
在C语言中,带头结点的单链表是一种常见的数据结构,其节点通常包含一个指向下一个节点的指针和一些数据成员。下面是插入和删除节点的基本操作:
**1. 插入操作(在链表末尾插入):**
```c
struct Node {
int data; // 节点的数据部分
struct Node* next; // 指向下一个节点的指针
};
void insertAtEnd(struct Node** head_ref, int new_data) {
// 如果链表为空,创建一个新的节点并作为头节点
if (*head_ref == NULL) {
*head_ref = (struct Node*)malloc(sizeof(struct Node));
(*head_ref)->data = new_data;
(*head_ref)->next = NULL;
}
else {
// 否则,在最后一个节点之后添加新节点
struct Node* temp = *head_ref;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = (struct Node*)malloc(sizeof(struct Node)); // 分配空间
temp->next->data = new_data; // 设置新值
temp->next->next = NULL; // 新节点的下一个位置是NULL
}
}
```
**2. 删除操作(删除特定值的节点):**
```c
void deleteNode(struct Node** head_ref, int key) {
// 检查链表是否为空
if (*head_ref == NULL) {
return;
}
// 遍历链表,找到需要删除的节点
struct Node* temp = *head_ref, *prev = NULL;
while (temp != NULL && temp->data != key) {
prev = temp;
temp = temp->next;
}
// 如果找到了要删除的节点,处理边界情况
if (temp != NULL) {
// 如果待删除节点是第一个节点
if (prev == NULL) {
*head_ref = temp->next;
free(temp);
}
// 如果待删除节点不是第一个节点,更新前一个节点的next指针
else {
prev->next = temp->next;
free(temp);
}
}
}
```
阅读全文
相关推荐


















