One test case {-1,-1} fails- Any suggestion for interpretation of input.


  • 0
    V

    My code fails for one test case {-1,-1} . But I do not understand this input. Can someone suggest.

    class Solution {
    public:
        RandomListNode *copyRandomList(RandomListNode *head) {
            if(head == nullptr)
                return nullptr;
            if(head->next == nullptr)
            {
                RandomListNode * newnode = new RandomListNode(head->label);
                newnode->random = head->random;
                return newnode;
            } 
            
            RandomListNode *givenlist = head, *clonelist = nullptr;
            
            while(givenlist != nullptr)
            {
                RandomListNode * newnode = new RandomListNode(givenlist->label);
                newnode->next = givenlist->next;
                givenlist->next = newnode;
                givenlist = givenlist->next->next;            
            }        
            givenlist = head;
            while(givenlist!=nullptr)
            {
                if(givenlist->random == nullptr)
                {
                    givenlist->next->random = nullptr;
                }
                else
                {
                    givenlist->next->random = givenlist->random->next;
                }
                givenlist = givenlist->next->next;
            }
            givenlist = head;
            clonelist = givenlist->next;
            while(givenlist!=nullptr)
            {
                RandomListNode * temp = givenlist->next;
                givenlist->next = temp->next;
                if(temp->next != nullptr)
                    temp->next = temp->next->next;
                givenlist = givenlist->next;
            }
            return clonelist;
        }
    };
    

Log in to reply
 

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