Simple iterative solution with memory management


  • 0
    X

    I am not sure why none of the top C++ answers has memory deletion. Here is my simple solution with correct memory release. Would appreciate suggestions.

    ListNode* deleteDuplicates(ListNode* head) {
            ListNode dummy(0);
            dummy.next = head;
            ListNode *prev = &dummy;
            
            while (prev->next) {
                ListNode *cur = prev->next;
                if (cur->next && cur->next->val == cur->val) {
                    do {
                        ListNode* tmp = cur->next->next;
                        delete cur->next;
                        cur->next = tmp;
                    } while (cur->next && cur->next->val == cur->val);
                    prev->next = cur->next;
                    delete cur;
                } else {
                    prev = prev->next;
                }
            }
          
            return dummy.next;
    }
    

Log in to reply
 

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