个人解法:
迭代
/**
* 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) {
ListNode *newhead=new ListNode(0,head);
ListNode *p1=newhead;
ListNode *p2=newhead->next;
if(p2==nullptr)
return newhead->next;
while(p2!=nullptr)
{
if(p2->val==val)
{
p1->next=p2->next;
p2=p1->next;
}
else
{
p2=p2->next;
p1=p1->next;
}
}
return newhead->next;
}
};
官方题解:递归(感觉好秀)
/**
* 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 head;
head->next=removeElements(head->next,val);
return head->val==val?head->next:head;
}
};
小萌新个人笔记,欢迎大佬批评指正