There is error about" Next pointer of node with label -1 from the original list was modified."Why?


  • 0
    L
      RandomListNode *copyRandomList(RandomListNode *head) {
       
       if( head == NULL ){
           return NULL;
       }
    
       RandomListNode *p1 = head;
       RandomListNode *p2 = NULL;
       RandomListNode *p2_loop = NULL;
       RandomListNode *p2_head = NULL;
       map<RandomListNode*,RandomListNode*>node_map;
       while(p1){
    
           RandomListNode *tmp = new RandomListNode(p1->label);
           tmp->next = p1->next;
           p1->next = tmp;
           p1 = tmp->next;
       }
    
       p1 = head;
       while(p1){
         if(p1->random){
             p1->next->random = p1->random->next;
         }
         p1 = p1->next->next;
       }
    
       p2_head = p2 = head->next;
       while(p2->next &&p2->next->next){
          p2->next = p2->next->next;
          p2 = p2->next;
       }
       return p2_head;
        }
    

    When I submit,it will report as below?Why?I have tested on my machine,it will output -1 in fact.

    Input:	{-1,#}
    Output:	Next pointer of node with label -1 from the original list was modified.
    Expected:	{-1,#}
    

    And I change this code

           p2_head = p2 = head->next;
           while(p2->next &&p2->next->next){
              p2->next = p2->next->next;
              p2 = p2->next;
           }
    

    to

     p1 = head;
       while(p1){
    
           p2 = p1->next;
           p1->next = p2->next;
           p1 = p1->next;
           if(p2_head==NULL){
              p2_head = p2;
              p2_loop = p2;
           }
           else{
              p2_loop->next = p2;
              p2_loop = p2;
           }
       }
    
       return p2_head;
    

    And it is acceped.But I think these 2 code can take the same function,just output the new list.Why the first code can't be accepted?What is this error means?


  • 1
    P

    you make changes to the original list and forget to restore the original list


  • 0
    L

    got it now.thanks


Log in to reply
 

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