遍历一遍链表即可:
/**
* 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==NULL)
return NULL;
ListNode *p=head;
while(head!=NULL&&head->val==val)
{
head=head->next;
}
p=head; //deal with head node
while(head!=NULL&&head->next!=NULL)
{
if(head->next->val==val)
{
head->next=head->next->next;
}
else
head=head->next;
}
return p;
}
};