C++ Solution with memory deallocation


  • 0
    J
    ListNode* deleteDuplicates(ListNode* head) {
            if (!head) return head;
            ListNode *dummyHead = new ListNode(0);
            dummyHead->next = head;
            
            ListNode *iterator = dummyHead;
            ListNode *candidate = head;
            
            while (candidate) {
                int count = 0;
                while (candidate && candidate->next && candidate->val == candidate->next->val) {
                    ListNode *toDelete = candidate;
                    candidate = candidate->next;
                    delete toDelete;
                    count++;
                }
                if (count > 0) {
                    ListNode *toDelete = candidate;
                    candidate = candidate->next;
                    iterator->next = candidate;
                    delete toDelete;
                } else {
                    iterator = iterator->next;
                    candidate = candidate->next;
                }
            }
            
            return dummyHead->next;
    }
    

Log in to reply
 

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