Remove all elements from a linked list of integers that have value val .
样例
Given 1->2->3->3->4->5->3 , val = 3, you should return the list as 1->2->4->5
class Solution {
public:
ListNode *removeElements(ListNode *head, int val) {
if(!head)
return nullptr;
while(head&&head->val==val){
ListNode *p=head;
head=head->next;
free(p);
}
ListNode *ptr=head;
ListNode *q;
while(ptr){
if(ptr->val==val){
if(!ptr->next){
q->next=NULL;
free(ptr);
}else{
ListNode *tmp=ptr->next;
ptr->val=tmp->val;
ptr->next=tmp->next;
free(tmp);
}
}else{
q=ptr;
ptr=ptr->next;
}
}
return head;
}
};
|