用c语言写代码删除链表中等于给定值 val 的所有节点并注释
时间: 2023-05-20 22:06:52 浏览: 85
以下是用 C 语言写的删除链表中等于给定值 val 的所有节点的代码,并附有注释:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
struct ListNode {
int val;
struct ListNode *next;
};
// 定义删除链表中等于给定值 val 的所有节点的函数
struct ListNode* removeElements(struct ListNode* head, int val) {
// 如果链表为空,直接返回
if (head == NULL) {
return NULL;
}
// 如果链表头节点的值等于 val,需要特殊处理
while (head != NULL && head->val == val) {
head = head->next;
}
// 定义两个指针,分别指向当前节点和前一个节点
struct ListNode *curr = head;
struct ListNode *prev = NULL;
// 遍历链表,删除值等于 val 的节点
while (curr != NULL) {
if (curr->val == val) {
// 如果当前节点的值等于 val,删除当前节点
if (prev != NULL) {
prev->next = curr->next;
}
free(curr);
curr = prev->next;
} else {
// 如果当前节点的值不等于 val,继续遍历
prev = curr;
curr = curr->next;
}
}
return head;
}
int main() {
// 创建链表
struct ListNode *head = (struct ListNode*)malloc(sizeof(struct ListNode));
head->val = 1;
head->next = (struct ListNode*)malloc(sizeof(struct ListNode));
head->next->val = 2;
head->next->next = (struct ListNode*)malloc(sizeof(struct ListNode));
head->next->next->val = 3;
head->next->next->next = (struct ListNode*)malloc(sizeof(struct ListNode));
head->next->next->next->val = 2;
head->next->next->next->next = NULL;
// 删除链表中等于给定值 val 的所有节点
int val = 2;
head = removeElements(head, val);
// 输出删除后的链表
struct ListNode *curr = head;
while (curr != NULL) {
printf("%d ", curr->val);
curr = curr->next;
}
printf("\n");
return 0;
}
```
注:这段代码使用了链表的基本操作,包括创建链表、遍历链表、删除节点等。其中,删除链表中等于给定值 val 的所有节点的函数 removeElements 的实现思路是:先处理头节点,再遍历链表删除值等于 val 的节点。
相关推荐
![-](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)