https://leetcode-cn.com/problems/remove-linked-list-elements/
思路一:迭代。注意需要删除头节点的情况(可以新增一个伪头节点,方便操作)。
/**
* 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)
return head;
ListNode myhead(0);
myhead.next=head;
ListNode *pre=&myhead,*cur=head;
while(cur){
if(cur->val==val){
ListNode *nxt=cur->next;
pre->next=nxt;
delete(cur);
cur=nxt;
}
else
pre=cur,cur=cur->next;
}
return myhead.next;
}
};
思路二:递归处理,在拿到下一个节点之后,判断当前节点的值是否等于 v a l val 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)
return head;
ListNode *tmp=removeElements(head->next,val);
if(head->val==val){
delete(head);
return tmp;
}
head->next=tmp;
return head;
}
};