用指针处理单项链表删除操作。c语言
时间: 2024-05-12 21:13:30 浏览: 9
单项链表删除节点的基本步骤是:
1. 找到待删除节点的前一个节点。
2. 将待删除节点从链表中断开。
3. 释放待删除节点的内存空间。
下面是使用指针来处理单项链表删除操作的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
/* 定义单项链表节点 */
typedef struct node {
int data; // 节点数据
struct node *next; // 指向下一个节点的指针
} Node;
/* 删除节点 */
void delete_node(Node **head, int value) {
Node *prev = NULL; // 待删除节点的前一个节点
Node *curr = *head; // 当前节点
// 遍历链表,找到待删除节点的前一个节点
while (curr != NULL && curr->data != value) {
prev = curr;
curr = curr->next;
}
// 如果链表中没有要删除的节点,直接返回
if (curr == NULL) {
return;
}
// 如果待删除节点是头节点,更新头指针
if (prev == NULL) {
*head = curr->next;
} else {
prev->next = curr->next;
}
// 释放待删除节点的内存空间
free(curr);
}
/* 打印链表 */
void print_list(Node *head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
/* 测试 */
int main() {
// 创建链表 1 -> 2 -> 3 -> 4 -> 5
Node *head = (Node*)malloc(sizeof(Node));
head->data = 1;
head->next = (Node*)malloc(sizeof(Node));
head->next->data = 2;
head->next->next = (Node*)malloc(sizeof(Node));
head->next->next->data = 3;
head->next->next->next = (Node*)malloc(sizeof(Node));
head->next->next->next->data = 4;
head->next->next->next->next = (Node*)malloc(sizeof(Node));
head->next->next->next->next->data = 5;
head->next->next->next->next->next = NULL;
// 删除节点 3
delete_node(&head, 3);
// 打印链表
print_list(head);
return 0;
}
```
在上面的代码中,`delete_node` 函数使用双重指针 `head` 来表示头指针的地址,这样可以在删除头节点时更新头指针。函数中通过遍历链表找到待删除节点的前一个节点,并将待删除节点从链表中断开。最后,函数释放待删除节点的内存空间。函数 `print_list` 用于打印链表。在 `main` 函数中,我们创建了一个链表 1 -> 2 -> 3 -> 4 -> 5,并删除了节点 3,然后打印剩余的链表。
相关推荐
![md](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)