链表操作,注意保护现场。
迭代
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
if(!head) return NULL;
ListNode *dummy = new ListNode(-1);
auto cur = dummy;
dummy->next = head;
while(cur){
if(cur->next && cur->next->val == val) cur->next = cur->next->next;
else cur = cur->next;
}
return dummy->next;
}
};
递归
class Solution {
public:
ListNode *removeElements(ListNode *head, int val){
if(!head) return head;
head->next = removeElements(head->next, val);
return head->val == val ? head->next : head;
}
};