Possible memory leaking


  • 0
    Y

    I get my code accepted, but I'm worrying that the steps in my code would cause a memory leak. By letting one iterator's next directly point to the node with a different value, I think I omit the ones that's in between. I tried to modify the code to release the memory of those duplicate node, but I get a compiler error:

    Line 39: expected unqualified-id before 'return'
    

    What can I do to make the second version of code working?

    This is the correct one (without releasing memory):

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode *deleteDuplicates(ListNode *head) {
            if (head==NULL)
                return head;
            ListNode *iterator1=head;
            ListNode *iterator2=head;
            while((*iterator2).next!=NULL)
            {
                iterator2=(*iterator2).next;
                if((*iterator2).val!=(*iterator1).val)
                {
                    (*iterator1).next=iterator2;
                    iterator1=iterator2;
                }
                else
                    (*iterator1).next=NULL;
                
            }
            
            return head;
            
        }
    };
    

    This is the one with error (try to release memory):

    class Solution {
    public:
        ListNode *deleteDuplicates(ListNode *head) {
            if (head==NULL)
                return head;
            ListNode *iterator1=head;
            ListNode *iterator2=head;
            ListNode *temp;
            while((*iterator2).next!=NULL)
            {
                if((*iterator1).next==NULL)
                {
                   // Here I try to delete the skipped node
                    temp=iterator2;
                    iterator2=(*iterator2).next;
                    delete *temp;
                }
                else
                    iterator2=(*iterator2).next;
                    
                if((*iterator2).val!=(*iterator1).val)
                {
                    (*iterator1).next=iterator2;
                    iterator1=iterator2;
                }
                else
                    (*iterator1).next=NULL;
                }
                
            }
            
            return head;
            
        }
    };

  • 2
    S

    First of all, it should be 'delete temp' rather than 'delete *temp'; secondly, there is one too many '}' after the last 'else' clause.


Log in to reply
 

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