C++ easy solution, no memory leak problem!


  • 0
    M
    ListNode* deleteDuplicates(ListNode* head) {
        ListNode* dummy = new ListNode(0);
        dummy->next = head;
        ListNode* cur = dummy;
        while (cur->next && cur->next->next) {
            if (cur->next->val == cur->next->next->val) {
                ListNode* trash = cur->next;
                cur->next = cur->next->next;
                delete trash;
            } else {
                cur = cur->next;
            }
        }
        head = dummy->next;
        delete dummy;
        return head;
    }

  • -1
    Z

    not sure if this really handle the memory leak;

    in your if condition, you first made a duplicate of node(cur->next) named "trash", then you just deleted the duplicate without considering the real cur-> next still exist. maybe you can use & instead of * in the code.


Log in to reply
 

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