移除链表元素
题目要求
删除链表中等于给定值val的所有节点。
示例1:
输入:1->2->6->3->4->5->6,val = 6
输出:1->2->3->4->5
思路
如果数组是空数组,那么直接返回头结点。如果数组全是目标节点,那么就释放所有空间,并且将头结点置空,如果数组前面仅仅只是有目标节点,将这些目标节点跳过,找到第一个不是目标节点的数,从这个节点开始,进行一快一慢指针的查找,快指针负责找和val值一样的节点,慢指针负责跳过,并将val空间释放,next指针置空。
图解
代码实现
struct ListNode* removeElements(struct ListNode* head, int val){
if (head == NULL)
{
return head;
}
while (head != NULL && head->val == val)
{
if (head->next == NULL)
{
head->next = NULL;
head = NULL;
return head;
}
head = head->next;
}
//快
struct ListNode* a = head->next;
//慢
struct ListNode* b = head;
while (a != NULL)
{
//判断是否是目标值
if (a->val == val)
{
struct ListNode* c = a->next;
b->next = c;
a->next = NULL;
free(a);
a = c;
}
else
{
b = a;
a = a->next;
}
}
return head;
}