给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。
示例 1:

输入:head = [1,2,6,3,4,5,6], val = 6
输出:[1,2,3,4,5]
示例 2:
输入:head = [], val = 1
输出:[]
示例 3:
输入:head = [7,7,7,7], val = 7
输出:[]
提示:
好,看完题目的描述,我们来分析一下如何去求解这道题目
然后我们通过这段代码来给大家分析一下

struct ListNode* cur = head;
struct ListNode* tail, *newhead;
tail = newhead = NULL;

if(tail == NULL){ //第一次拿过来
newhead = tail = cur;

tail->next = cur;
tail = tail->next;
```>
- 接着我们可以看到此时的cur所指向的结点值为6,是我们需要的待删结点,此时就需要执行删除的逻辑,将其从链表中删除即可,然后的话既然它不是我们需要的元素,就不需要将其链接到新链表中,直接进行以下代码的操作即可
- 有一点,不要忘了保存待删结点的下一个结点,否则free之后就找不到了
```c
struct ListNode* nextNode = cur->next; //首先保存下一结点
free(cur);
cur = nextNode;



此处为大家以视频的形式展现,温馨提示:【如果太模糊请左右拖动一下】
LeetCode转VS调试
struct ListNode* cur = head;
struct ListNode* tail, *guard;
tail = guard = (struct ListNode*)malloc(sizeof(struct ListNode));
if(cur->val != val){
tail->next = cur;
tail = tail->next;
cur = cur->next;
}
给出两种方法的代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeElements(struct ListNode* head, int val){
if(head == NULL){
return head;
}
struct ListNode* cur = head;
struct ListNode* tail, *newhead;
tail = newhead = NULL;
while(cur)
{
//1.结点不为待删结点,拿过来尾插
if(cur->val != val){
if(tail == NULL){ //第一次拿过来
newhead = tail = cur;
}else{ //后续的尾插
tail->next = cur;
tail = tail->next;
}
cur = cur->next;
}else{ //2.结点为待删结点,实行删除结点操作
struct ListNode* nextNode = cur->next; //首先保存下一结点
free(cur);
cur = nextNode;
}
}
if(tail)
tail->next = NULL;
return newhead;
}
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeElements(struct ListNode* head, int val){
if(head == NULL){
return head;
}
struct ListNode* cur = head;
struct ListNode* tail, *guard;
tail = guard = (struct ListNode*)malloc(sizeof(struct ListNode));
while(cur)
{
//1.结点不为待删结点,拿过来尾插
if(cur->val != val){
tail->next = cur;
tail = tail->next;
cur = cur->next;
}else{ //2.结点为待删结点,实行删除结点操作
struct ListNode* nextNode = cur->next; //首先保存下一结点
free(cur);
cur = nextNode;
}
}
//tail不可能为空,一开始已经开出空间指向第一个结点
tail->next = NULL;
struct ListNode*next = guard->next;
free(guard);
return next;
}
以上就是本文所要描述的所有内容,感谢您对本文的观看,如有疑问请于评论区留言或者私信我都可以🍀