C++ Solution, a bit verbose but easy to understand


  • 0
    A

    Basic idea is to keep the (potential) start of a duplicate part in dupStart and use a flag dup to record whether it is actually duplicate or not. Comparison is always done against dupStart. Only link it to the new list once confirmed it's not duplicate. I think the idea is clear but my implementation has some duplicate code. Please help improve. Thanks.

    ListNode* deleteDuplicates(ListNode* head) {
        if (!head || !head->next) return head;
        ListNode dummy(-1), *p = &dummy;
        ListNode *dupStart = head;
        bool dup = false;
        while (head = head->next) {
            if (head->val == dupStart->val) {
                dup = true;
            } else {
                if (!dup) {
                    p->next = dupStart;
                    p = p->next;
                } else {
                    dup = false;
                }
                dupStart = head;
            }
        }
        if (dup) {
            p->next = NULL;
        } else {
            p->next = dupStart;
        }
        return dummy.next;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.