C++ 12 ms beats 73% Two solutions: one by one & fast just for fun


  • 0
    P
    ListNode* deleteDuplicates_SimpleOneByOne_16ms(ListNode* head) 
    {
        ListNode* node  = head;
        while(node && node->next)
        {
            if(node->val == node->next->val)
            {
                delete node->next;
                node->next = node->next->next;
            }
            else
                node = node->next;
        }
        
        return head;
    }
    
    
    ListNode* deleteDuplicates_Fast_12ms(ListNode* head) 
    {
        ListNode* node  = head;
        ListNode* prev = 0;
        while(node && node->next)
        {
            if(node->val == node->next->val)
            {
                if(prev == 0) prev = node;
            }
            else if(prev)
            {
                prev->next = node->next; // cheating here since I'm not deleting duplicated nodes, just for fun...
                prev = 0;
            }
            node = node->next;
        }
        
        if(prev) prev->next = node->next;
    
        return head;
    }

Log in to reply
 

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