1. 程式人生 > >138. Copy List with Random Pointer

138. Copy List with Random Pointer

poi pub 第一次 一個 新建 lin 對象 addition hat

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