138 Copy List with Random Pointer Input: {-1,-1} Output: {-1,#} Expected: {-1,-1} 10 / 11 test cases passed.


  • 1
    O

    138 Copy List with Random Pointer Input: {-1,-1} Output: {-1,#} Expected: {-1,-1}
    when it runs in my computer on VS2008,Input: {-1,-1} Output: {-1,-1}, the Output is equal to the Expected, I can not know the reason?

    code:

    enter image description here

    RandomListNode *copyRandomList(RandomListNode *head) 
    {
    	if(head==NULL)return NULL;
    	if(head->next==NULL)return new RandomListNode(head->label);
    	RandomListNode *p=head;
    	RandomListNode *res=NULL;
    	RandomListNode *pNew=NULL;
    	RandomListNode *pNext=NULL;
    	while (p)
    	{
    		pNext=p->next;
    		pNew=new RandomListNode(p->label);
    		p->next=pNew;
    		pNew->next=pNext;
    		p=pNext;
    	}
    	p=head;
    	while(p)
    	{
    		if(p->random)p->next->random=p->random->next;
    		p=p->next->next;
    	}
    	p=head;
    	RandomListNode *p1=p->next;
    	while(p1->next)
    	{
    		if(res==NULL)res=p1;
    		p->next=p->next->next;
    		p=p->next;
    		p1->next=p->next;
    		p1=p1->next;
    	}
    	p->next=NULL;
    	p1->next=NULL;
    	return res;
    }

  • 0
    J

    I have solved your question. The case:{-1,-1} represent only one node in list, and the random point to itself.


Log in to reply
 

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