48. 单链表删除数字

RT

dummy节点的使用使得代码更加简洁,如果不用dummy节点,则要用如下两种或类似写法:

    ListNode* removeElements(ListNode* head, int val) {
        if (head == NULL) {
            return head;
        }

        while(head != NULL && head->val == val) {
            head = head->next;
        }

        ListNode* p = head;
        ListNode* pre = NULL;
        while(p != NULL) {
            if (p->val == val && pre != NULL) {
                pre->next = p->next;
            } else {
                pre = p;
            }
            p = p->next;
        }

        return head;
    }
    ListNode* removeElements(ListNode* head, int val) {
        if (head == NULL) {
            return head;
        }

        while(head != NULL && head->val == val) {
            head = head->next;
        }

        ListNode* p = head;
        while(p && p->next) {
            if (p->next->val == val) {
                p->next = p->next->next;
            } else {
                p = p->next;
            }
        }

        return head;
    }