C++ O(N) timecomplexity


  • 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;
       p = head;
       
       while(p != NULL && p->next != NULL)
       {
            newlist = p->next;
            p->next = p->next->next;
            if(newlist->next!= NULL)
            {
                newlist->next = newlist->next->next;
            }
            else{
                newlist->next = NULL;
            }
            
            p=p->next;
       }
       
       return newhead;
    }
    

    };


Log in to reply
 

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