给你一个链表的头节点 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
输出:[]
思路:
使用两个指针,prev和cur,cur记录当前指针位置,prev记录前一个位置
如果cur->val!= val,那么prev = cur,cur = cur->next,继续向后查找
如果cur->val == val,prev->next = cur->next, 释放cur,将cur置为prev->next
还要考虑一种情况,就是头节点的val等于val,我们要删除第一个节点,新的头结点是下一个结点
struct ListNode
{
int val;
struct ListNode* next;
};
struct ListNode* removeElements(struct ListNode* head, int val)
{
struct ListNode* cur = head;
struct ListNode* prev = NULL;
while (cur != NULL)
{
if (cur->val == val)
{
//1.头删
if (cur == head)
{
head = cur ->next;
free(cur);
cur = head;
}
else
{
//2.中间删除
prev->next = cur->next;
//释放空间
free(cur);
//cur = NULL;
cur = prev->next;
}
}
else
{
//继续向后查找
prev = cur;
cur = cur->next;
}
}
//返回新的头
return head;
}
//测试代码
int main()
{
struct ListNode* n1 = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* n2 = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* n3 = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* n4 = (struct ListNode*)malloc(sizeof(struct ListNode));
n1->val = 7;
n2->val = 7;
n3->val = 7;
n4->val = 7;
n1->next = n2;
n2->next = n3;
n3->next = n4;
n4->next = NULL;
struct ListNode* head = removeElements(n1,7);
return 0;
}