Remove all elements from a linked list of integers that have value val.
Example
Given: 1 –> 2 –> 6 –> 3 –> 4 –> 5 –> 6, val = 6
Return: 1 –> 2 –> 3 –> 4 –> 5
删除指定值的所有节点
方法一:依次遍历
/**
* 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) {
while(head !=NULL && head->val==val)
head=head->next;
ListNode *curr=head;
while(curr !=NULL && curr->next !=NULL)
{
if(curr->next->val==val)
curr->next=curr->next->next;
else
curr=curr->next;
}
return head;
}
};
方法二:递归
/**
* 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;
head->next=removeElements(head->next,val);
return head->val==val ? head->next:head;
}
};