/**
* Definition for singlylinked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
if (head==NULL){
return head;
}
ListNode* p=head;
while(p>next!=NULL){
if (p>next>val == val){
p>next = p>next>next;
}
else{
p=p>next;
}
}
if (head>val==val)
head=head>next;
return head;
}
};
32ms C++ AC solution


class Solution { public: ListNode* removeElements(ListNode* head, int val) { if (head==NULL){ return head; } ListNode* p=head; while(p>next!=NULL){ if (p>next>val == val){ auto freeNode = p>next; p>next = p>next>next; free(freeNode); } else{ p=p>next; } } if (head>val==val) head=head>next; return head; } };


share my solution similar to yours;
ListNode* removeElements(ListNode* head, int val) { while(head && head>val == val) head = head>next; if(head == nullptr) return nullptr; ListNode *p = head>next; ListNode *prev = head; while(p) { if(p>val == val) { prev>next = p>next; p = p>next; } else { prev = p; p = p>next; } } return head; }

@benyin You're forgetting a free on your very last conditional before you return. In the case where the head has the
val
you want to skip over it but also free the old head right?