/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
if(head==NULL){
return head;
}
if(head->next==NULL){
if(head->val!=val){
return head;
}else{
return NULL;
}
}
ListNode* p=head->next;
ListNode* q=head;
ListNode* s;
while(p->next!=NULL){
if(p->val==val){
s=p;
p=p->next;
q->next=p;
delete(s);
}else{
p=p->next;
q=q->next;
}
}
if(p->val==val){
delete(p);
q->next=NULL;
}
if(head->val==val){
if(head->next!=NULL){
s=head;
head=head->next;
}else{
return NULL;
}
}
return head;
}
};
最简单直白的写法