Wednesday, November 13, 2013

Leetcode problem : Copy List with Random Pointer

Copy List with Random Pointer

A linked list is given such that each node contains an additional
random pointer which could point to any node in the list or null.
Return a deep copy of the list.

Code

void DFS_crl(RandomListNode *v,RandomListNode *u,map<RandomListNode*,RandomListNode*>& nodeMap){
    RandomListNode *w1 = v->next;
    if(w1){
        if(nodeMap.find(w1) != nodeMap.end()){
            u->next = nodeMap[w1];
        }
        else{
            u->next = new RandomListNode(w1->label);
            nodeMap.insert(make_pair(w1,u->next));
            DFS_crl(w1,u->next,nodeMap);
        }   
    }
    RandomListNode *w2 = v->random;
    if(w2){
        if(nodeMap.find(w2) != nodeMap.end()){
            u->random = nodeMap[w2];
        }
        else{
            u->random = new RandomListNode(w2->label);
            nodeMap.insert(make_pair(w2,u->random));
            DFS_crl(w2,u->random,nodeMap);
        }
    }
}

RandomListNode *copyRandomList(RandomListNode *head) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
    if(!head)
        return 0;
    map<RandomListNode*,RandomListNode*> nodeMap;
    RandomListNode* u = new RandomListNode(head->label);
    DFS_crl(head,u,nodeMap);
    return u;
}

No comments:

Post a Comment