Sharing my neat C++ solution


  • 0
    B

    tricks

    1. dummy node (but need to be careful to get rid of some cute situations with the dup values)
    2. save a dup value, and use node->next->val = dup and node->next->val == node->next->next->val to examine the duplications
     class Solution {
    public:
        ListNode* deleteDuplicates(ListNode* head) {
            if(!head || !head->next) return head;
            ListNode *dummy = new ListNode(0), *cur = dummy, *run = dummy;
            // to get rid of some cute situations
            int dup = 2*head->val;
            while(dup == head->val || dup == head->next->val) dup += 2*head->val+2*head->next->val+1;
            dummy->next = head;
            while(run->next) {
                if(run->next->val == dup || (run->next->next && run->next->val == run->next->next->val)) {
                    if(run->next->next && run->next->val == run->next->next->val) dup = run->next->val;
                    run = run->next;
                    if(cur->next) cur->next = nullptr;
                } else {
                    cur->next = run->next;
                    cur = cur->next;
                    run = run->next;
                }
            }
            return dummy->next;
        }
    };
    

Log in to reply
 

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