Share a 4ms C solution which need be optimized


  • 0
    S
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     struct ListNode *next;
     * };
     */
    struct ListNode *deleteDuplicates(struct ListNode *head) {
        if(head && head->next)
        {
            struct ListNode *p1, *p2;
            
            if(head->val != head->next->val)
            {
                p1 = head;
                p2 = head->next;
                while(p2 && p2->next)
                {
                    if(p2->val != p2->next->val)
                    {
                        p1 = p2;
                        p2 = p2->next;
                    }
                    else
                    {
                        while(p2->next->next &&  p2->next->next->val == p2->val)
                        {
                            p2 = p2->next;
                        }
                        p1->next = p2->next->next;
                        p2 = p1->next;
                    }
                }
                
                return head;
            }
            else
            {
                while(head->next && head->val == head->next->val)
                {
                    head = head->next;
                }
                
                p1 = head;
                p2 = head->next;
                while(p2 && p2->next)
                {
                    if(p2->val != p2->next->val)
                    {
                        p1 = p2;
                        p2 = p2->next;
                    }
                    else
                    {
                        while(p2->next->next &&  p2->next->next->val == p2->val)
                        {
                            p2 = p2->next;
                        }
                        p1->next = p2->next->next;
                        p2 = p1->next;
                    }
                }
                
                return head->next;
            }
                
        }
        
        return head;
    }

Log in to reply
 

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