138. Copy List with Random Pointer

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

 

posted @ 2017-10-06 14:23  Tsunami_lj  阅读(121)  评论(0编辑  收藏  举报