Passed all my own written test cases, but still fail here


  • 0
    C
    /**
     * Definition for singly-linked list with a random pointer.
     * struct RandomListNode {
     *     int label;
     *     RandomListNode *next, *random;
     *     RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
     * };
     */
    class Solution {
    public:
       RandomListNode *copyRandomList(RandomListNode *head) 
        {
            if(head==NULL)
                return head;
            RandomListNode *p=head;
            p=p->next;
            RandomListNode *q=new RandomListNode(p->label);
            RandomListNode *q1=q;
            unordered_map<RandomListNode*, RandomListNode*> hashMap;
            hashMap.clear();
            hashMap.insert(make_pair(head, q));
            // deep copy the list with all the next pointers
            while(p!=NULL)
            {
                RandomListNode *tmp=new RandomListNode(p->label);
                q->next=tmp;
                q=q->next;
                hashMap.insert(make_pair(p,q));
                p=p->next;
            }
            p=head;
            q=q1;
            // deep copy the random pointers
            while(p!=NULL)
            {
                if(p->random!=NULL)
                    q->random=hashMap[p->random];
                p=p->next;
                q=q->next;
            }
            q=q1;
    		return q;
        }
    };

Log in to reply
 

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