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

Leetcode: Copy List with Random Pointer

时间:2014-11-25 22:44:23      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   sp   for   on   div   log   

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.

分析:因为有random pointer,我们需要保存原结点对应的新结点来完成deep copy。时间复杂度为O(n), 空间复杂度为O(n)。

class Solution {
public:
    RandomListNode *copyRandomList(RandomListNode *head) {
        if(head == NULL) return NULL;
        unordered_map<RandomListNode *, RandomListNode *> pmap;
        
        for(RandomListNode *p = head; p; p = p->next){
            RandomListNode * q = new RandomListNode(p->label);
            pmap[p] = q;
        }
        
        for(RandomListNode *p = head; p; p = p->next){
            if(p->next)
                pmap[p]->next = pmap[p->next];
            if(p->random)
                pmap[p]->random = pmap[p->random];
        }
        
        return pmap[head];
    }
};

 

Leetcode: Copy List with Random Pointer

标签:style   blog   io   color   sp   for   on   div   log   

原文地址:http://www.cnblogs.com/Kai-Xing/p/4121771.html

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