Weird question regarding copy list with random pointer

  • 0
    RandomListNode *copyRandomList(RandomListNode *head) {
            if(head == NULL) return NULL;
            RandomListNode *copyhead = new RandomListNode(head->label);
            copyhead->random = head->random;
            RandomListNode *ori = head->next;
            RandomListNode *oritemp;
            head->next = copyhead;
            RandomListNode *copy = copyhead;
            //copy to a new list "copyhead"
            while(ori != NULL)
                RandomListNode *copytemp = new RandomListNode(ori->label);
                copytemp->random = ori->random;
                copy->next = copytemp;;
                oritemp = ori->next;
                ori->next = copytemp;
                ori = oritemp;
                copy = copy->next;
            //assign the random pointers
            copy = copyhead;
            while(copy != NULL)
                if(copy->random != NULL)
                copy->random =  copy->random->next;
                copy = copy->next;
            return copyhead;

    Could anyone please explain why the above code cannot even pass [-1, #]?

    The weird thing is I can have the above code passed on my own machine without any problem.


Log in to reply

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