昨天做完那道题后推荐了这道题~类似的解法,但是通过率竟然挺低的
代码如下,就是用测试用例测一下,考虑多种情况做的。比如一开始都是val的情况,以及中间有val的情况
ListNode* removeElements(ListNode* head, int val) {
ListNode* first=head;
if(first==NULL) return 0;
else if(first!=NULL){
while(first->val==val){
if(first->next!=NULL){ //针对前几个是val,后面有其他值的
head=first->next;
first=first->next;
}
else{ //针对集合里都是val的
return NULL;
}
}
}
while(first->next!=NULL){
if(first->next->val==val){
first->next=first->next->next;
continue;
}
first=first->next;
}
return head;
}
ListNode* removeElements(ListNode* head, int val) {
if (head == NULL) return NULL;
if (val == head->val) return removeElements(head->next,val);
head->next = removeElements(head->next,val);
return head;
}