原题链接:Leecode 203. 移除链表元素
迭代·:
/**
* 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;
while(head && head->val==val)
{
head=head->next;
}
ListNode* root=head;
while(head && head->next)
{
if(head->next->val==val) head->next=head->next->next;
else head=head->next;
}
return root;
}
};
递归:
/**
* 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;
head->next=removeElements(head->next, val);
head= head->val==val ? head->next:head;
return head;
}
};