LeetCode 203. Remove Linked List Elements
Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val
, and return the new head.
Example 1:
Input: head = [1,2,6,3,4,5,6], val = 6
Output: [1,2,3,4,5]
method 1: 迭代
可能会连续删除多个元素,所以要用while
因为会访问next
的成员,所以必须确保next
不为空
ListNode* removeElements(ListNode* head, int val) {
if (!head) return head;
ListNode dummy = ListNode(0, head);
head = &dummy;
while (head) {
while (head->next && head->next->val == val) {
head->next = head->next->next;
}
head = head->next;
}
return dummy.next;
}
method 2: 递归
如果这个点需要删除,就返回next
,这样这个点就没了
ListNode* removeElements(ListNode* head, int val) {
if (!head) return head;
head->next = removeElements(head->next, val);
if (head->val == val) {
return head->next;
}
return head;
}