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

138. Copy List with Random Pointer

时间:2017-10-06 14:41:53      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:blog   class   链表   list   logs   dom   add   return   map   

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.

解法一:用一个map把原有的节点映射到新建的对象。遍历两遍,第一次新复制一个原有的链表,第二次做random的映射。时间复杂度O(n),空间复杂度O(n).

/**
 * Definition for singly-linked list with a random pointer.
 * struct RandomListNode {
 *     int label;
 *     RandomListNode *next, *random;
 *     RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
 * };
 */
class Solution {
public:
    RandomListNode *copyRandomList(RandomListNode *head) {
        if(!head)return {};
        map<RandomListNode*, RandomListNode*>hash;
        RandomListNode *res=NULL, *orig=head, *tail=NULL;
        while(head){
            RandomListNode* temp=new RandomListNode(head->label);
            if(!tail)res=tail=temp;
            else tail->next=temp,tail=tail->next;
            hash[head]=temp;
            head=head->next;
        }
        tail=res;
        while(orig){
            tail->random=hash[orig->random];
            tail=tail->next;
            orig=orig->next;
        }
        //tail->next=NULL;
        return res;
    }
};

解法二:在原有每个节点之后都插入一个新的节点,这样原有的节点都是新节点的pre,这样每次新的random都是前一个节点的random,最后再把这些新建的节点摘除下来,就是最后的结果。

/**
 * Definition for singly-linked list with a random pointer.
 * struct RandomListNode {
 *     int label;
 *     RandomListNode *next, *random;
 *     RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
 * };
 */
class Solution {
public:
    RandomListNode *copyRandomList(RandomListNode *head) {
        if(!head)return {};
        RandomListNode *orig=head, *copy;
        //insert new nodes after origin nodes
        while(head){
            copy=new RandomListNode(head->label);
            copy->next=head->next;
            head->next=copy;
            head=copy->next;
        }
        head=orig;
        while(head){
            copy=head->next;
            if(head->random)
                copy->random=head->random->next;
            head=copy->next;
        }
        RandomListNode *res=orig->next;
        head=orig;
        while(head){
            copy=head->next;
            head->next=copy->next;
            head=head->next;
            copy->next=head?head->next:NULL;
            
        }
        return res;
    }
};

 

138. Copy List with Random Pointer

标签:blog   class   链表   list   logs   dom   add   return   map   

原文地址:http://www.cnblogs.com/tsunami-lj/p/7631510.html

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