删除链表中等于给定值 val 的所有节点。
示例:
输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5
代码
struct ListNode* removeElements(struct ListNode* head, int val)
{
if(head ==NULL)
{
return head;
}
struct ListNode* newhead =NULL;
struct ListNode* tail=NULL;
struct ListNode* cur =head;
while(cur)
{
struct ListNode*next =cur->next;
if(cur->val != val)
{
if(newhead ==NULL)
{
newhead=tail=cur;
}
else
{
tail->next =cur;
tail=cur;
}
}
else
{
free(cur);
}
cur=next;
}
if(tail )
{
tail->next=NULL;
}
return newhead;
}