
cpp
/**
* 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 == nullptr)
{
return nullptr;
}
ListNode* _dummyhead = new ListNode(0);
_dummyhead->next = head;
ListNode* pre = _dummyhead;
ListNode* cur = _dummyhead->next;
while(cur)
{
if(cur->val == val)
{
ListNode* p = cur;
pre->next = cur->next;
cur = cur->next;
delete p;
}
else
{
cur = cur->next;
pre = pre->next;
}
}
return _dummyhead->next;
}
};
