码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode "Copy List with Random Pointer"

时间:2014-07-23 14:59:26      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   for   re   

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];
    }
};

LeetCode "Copy List with Random Pointer",布布扣,bubuko.com

LeetCode "Copy List with Random Pointer"

标签:style   blog   color   io   for   re   

原文地址:http://www.cnblogs.com/tonix/p/3862735.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!