C++ ,96ms,better than 90%


  • 0
    F

    class Solution {
    public:
    RandomListNode *copyRandomList(RandomListNode *head) {

       RandomListNode *newhead = NULL;
       RandomListNode *newlist = NULL;
       RandomListNode *p = head;
       
       if(head == NULL)
       {
           return NULL;
       }
       
       while(p != NULL)
       {
           RandomListNode *copynode = new RandomListNode(p->label);
           RandomListNode *next = p->next;
           p->next = copynode;
           copynode->next = next;
           p = next;
       }
       
       p = head;
       
       while(p != NULL &&  p->next != NULL)
       {
           if(p->random != NULL)
           {
               p->next->random = p->random->next;
           }
           
           p = p->next->next;
       }
       
       newhead = head->next;
       newlist = head->next;
       p = head;
       
       while(newlist != NULL && newlist->next != NULL)
       {
            p->next = p->next->next;
            newlist->next = newlist->next->next;
            newlist = newlist->next;
            p=p->next;
       }
       p->next = NULL;
       return newhead;
    }
    

    };


Log in to reply
 

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