May I kindly ask why I got memory limit exceeded for my random-copy-codes?


  • 0
    Z

    I implement my codes according to the "classical answer on Google". Looks correct and I tried it on my vs2010, which works well...

    RandomListNode *copyRandomList(RandomListNode *head) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            
        if(head==NULL)
    	    return NULL;
    
    	RandomListNode *tmp,*tmpnew;
    	RandomListNode *headnew;
    
    	//duplicate by insertion
    	for(tmp=head;tmp!=NULL;tmp=tmp->next)
    	{
    		RandomListNode *tmpnew = new RandomListNode(tmp->label);//new node
    		tmpnew->next = tmp->next;
    		tmp->next = tmpnew;
    	}
    
    	//tackle random
    	for(tmp=head;tmp!=NULL;tmp=tmp->next->next)
    	{
    		if(tmp->random!=NULL)
    			tmp->next->random = tmp->random->next;
    	}
    
    	// restore two lists
    	headnew = head->next;
    	for(tmp=head,tmpnew=headnew;tmp!=NULL;)
    	{
    		RandomListNode *n=tmp->next->next;
    
    		tmp->next = n;
    		tmpnew->next = n->next;
    
    		tmp=tmp->next;
    		tmpnew=tmpnew->next;
    	}
    	return headnew;
            
        }

  • 0

    Could you format your code by selecting your code and clicking on the {} button?


  • 0
    A
    This post is deleted!

  • 0
    T

    Try invoking, printRandomList(RandomListNode *head) passing the headnew that your function is returning. (on VS offcourse).
    Hope it helps !


  • 0
    W
    for(tmp=head;tmp!=NULL;tmp=tmp->next)
    {
        RandomListNode *tmpnew = new RandomListNode(tmp->label);//new node
        tmpnew->next = tmp->next;
        tmp->next = tmpnew;
    }
    

    I think this part is infinite loop and run out of your memory.


  • 0
    W

    It will be a good way for him to find the problem. ^_^


  • 0
    S

    I dont think this piece of code would work any where. When you are doing the insertion you should try to let the temp advance two nodes instead of one. Or infinite loop will occur


  • 0
    W

    In your first loop (generate a duplicate list), you may want to change tmp = tmp->next to tmp = tmp->next->next, since you already add one node after the original one.


  • 0
    M

    for(tmp=head;tmp!=NULL;tmp=tmp->next)
    {
    RandomListNode *tmpnew = new RandomListNode(tmp->label);//new node
    tmpnew->next = tmp->next;
    tmp->next = tmpnew;
    }

    tmp->next is changed before the looping at tmp=tmp->next


Log in to reply
 

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