方法一:迭代
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
if(head==nullptr)return nullptr;
ListNode*p=head,*q=nullptr;
while(p)
{
ListNode*k=nullptr;
if(head->val==val)
{
k=head;
head=head->next;
q=head;
p=p->next;
delete k;
}
else if(p->val==val)
{
k=p;
q->next=p->next;
p=p->next;
delete k;
}
else
{
q=p;
p=p->next;
}
}
return head;
}
};
方法二:加头指针
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode * dHead = new ListNode(-1);
dHead->next = head;
ListNode * prev = dHead;
while(prev->next)
{
if(prev->next->val == val)
{
ListNode * deletenode = prev->next;
prev->next = prev->next->next;
delete deletenode;
}
else
{
prev = prev->next;
}
}
return dHead->next;
}
};