删除链表中等于给定值 val 的所有节点。
/**
* Definition for singly-linked 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==nullptr)
{
return nullptr;
}
while(head->val==val)
{
if(head->next==nullptr)
{
return nullptr;
}
head=head->next;
}
ListNode *q=head,*p=head;
while(p->next!=NULL)
{
p=p->next;
if(p->val==val)
{
q->next=p->next;
}
else
{
q=p;
}
}
return head;
}
};