138. Copy List with Random Pointer

Posted 为了更优秀的你,加油!

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
    }
};

 

以上是关于138. Copy List with Random Pointer的主要内容,如果未能解决你的问题,请参考以下文章

138. Copy List with Random Pointer

138. Copy List with Random Pointer

138 Copy List with Random Pointer

138. Copy List with Random Pointer

138. Copy List with Random Pointer(js)

138. Copy List with Random Pointer