LeetCode 203.移除链表元素 C做法
思路:
由于是单链表,所以我们可以创建一个新的头结点newhead,把不是val的结点尾插在newhead中,而等于val的结点给释放,最后返回newhead。防止时间复杂度过高,我们再创建一个尾指针tail保存最新的尾插地址,这样仅需遍历一次就能完成尾插
代码:
struct ListNode* cur = head;
struct ListNode* newhead = NULL,*tail = NULL; //tail存储上次尾插的结点
while(cur)
{
if(cur->val != val)
{
if(tail == NULL)
{
tail = newhead = cur;
}
else
{
tail->next = cur;
tail = tail->next;
}
cur = cur->next; //这里不能与tail->next交换位置,不然cur也会被置空
tail->next = NULL; //防止尾插后tail->next还链接在被释放的节点上,所以要置空
}
else
{
struct ListNode* del = cur;
cur = cur->next;
free(del);
}
}
return newhead;