Remove Linked List Elements
Remove all elements from a linked list of integers that have value val.
Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5
实例
给定链表:1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
返回:1 --> 2 --> 3 --> 4 --> 5。
struct ListNode* removeElements(struct ListNode* head, int val) {
struct ListNode *pre = head, *cur = head;
while(cur)
{
if(cur->val == val)
{
if(cur == head)
{
pre = head = cur->next;
free(cur);
cur = head;
}
else
{
pre->next = cur->next;
free(cur);
cur = pre->next;
}
}
else
{
pre = cur;
cur = cur->next;
}
}
return head;
}