LeetCode "Copy List with Random Pointer"

Two passes: all pointer linking info will be recorded in 1st pass - to hashmap; 2nd pass recover the pointer relationship from hashmap. 1A! 

class Solution {
public:
    RandomListNode *copyRandomList(RandomListNode *head) {
        if (!head) return NULL;

        vector<RandomListNode *> vec;
        unordered_map<RandomListNode *, unsigned> ptrMap;
        //    1st pass
        RandomListNode *p = head;
        unsigned i = 0;
        while (p)
        {
            RandomListNode *pCurr = new RandomListNode(p->label);
            pCurr->random = p->random;
            pCurr->next = p->next;
            vec.push_back(pCurr);
            ptrMap.insert(make_pair(p, i ++));
            p = p->next; 
        }
        //    2nd pass
        for (int i = 0; i < vec.size(); i++)
        {
            RandomListNode *pCurr = vec[i];
            if (pCurr->next)    pCurr->next = vec[ptrMap[pCurr->next]];
            if (pCurr->random)    pCurr->random = vec[ptrMap[pCurr->random]];
        }
        return vec[0];
    }
};
原文地址:https://www.cnblogs.com/tonix/p/3862735.html