玩命加载中 . . .

203-移除链表元素


LeetCode 203. Remove Linked List Elements

LeetCode-203

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;
}

文章作者: kunpeng
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 kunpeng !
  目录