C code in 32 ms :) Is the solution possible if there is Loop ? Can it be solved by start and end Pointer ?


  • 0
    S

    struct RandomListNode *copyRandomList(struct RandomListNode *head) {

    //add a node between the LL
    
    struct RandomListNode *addNode=NULL;
    struct RandomListNode *curr=head;
    struct RandomListNode *Nextnode=NULL;
    struct RandomListNode *copypointer=head;
    struct RandomListNode *decouple=head;
    struct RandomListNode *prev=NULL;
    struct RandomListNode *randomNext=NULL;
    
    
      if(head==NULL)
          return head;
    
    while(curr)
    {
    	Nextnode=curr->next;
    	addNode=(struct RandomListNode *)malloc(sizeof(struct RandomListNode *));
    
    	addNode->label=curr->label;
    	addNode->next=curr->next;
    	curr->next=addNode;
    	addNode->random=NULL;
    
    	curr=Nextnode;
    }
    
    //copy random pointer
    
    while(copypointer)
    {
        randomNext=copypointer->next;
          if(copypointer->random)
        	randomNext->random=copypointer->random->next;
    	copypointer=randomNext->next;
    }
    
      //get the duplicate LL head
    
      struct RandomListNode* duplicate = (head == NULL? NULL:head->next);
    
    
    //decouple the original
    
    while(decouple)
    {
    	Nextnode=decouple->next;
    
                decouple->next=Nextnode->next;//originalnode next points to its original next
    
                if(Nextnode->next)
                    Nextnode->next=Nextnode->next->next;
    
    	decouple=decouple->next;//it is safe to do this now
    
    
    }
    
    
    return duplicate;
    

    }


Log in to reply
 

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