首页 > 其他 > 详细

LeetCode "Copy List with Random Pointer"

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

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"

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!