首页 > 代码库 > [leetcode] Copy List with Random Pointer

[leetcode] Copy List with Random Pointer

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.

思路:

不会。看着提示显示的哈希表的题目,不清楚怎么用哈希表存储random的节点。看了别人的做法,豁然开朗。unordered_map存储的是本链表的某个节点和复制之后的链表对应的节点,即链表的第二个节点对应复制链表的第二个节点(深度复制,那当然两个节点一样)。第一步完成之后,链表的next域全部复制完成,同时节点也对应起来了。第二步,假设p1与p2为对应的节点,那么p1->random节点也会对应p2->random,所以又map[p1]->random = map[p1->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==NULL)            return NULL;        unordered_map<RandomListNode*, RandomListNode*> map;        RandomListNode *head2 = new RandomListNode(head->label);        RandomListNode *p1 = head, *p2 = head2;        map[p1] = p2;        p1 = p1->next;        while(p1) {            RandomListNode *tmp = new RandomListNode(p1->label);            map[p1] = tmp;            p2->next = tmp;            p2 = tmp;            p1 = p1->next;        }        p1 = head;        while(p1) {            if(p1->random)                map[p1]->random = map[p1->random];            p1 = p1->next;        }        return head2;    }};
View Code

后话:

还是参考了一篇博客。上面的方法空间复杂度为O(n),还有一种O(1)的方法,感觉太牛逼了,看看就好,第一种方法要吃透,哈希表存储的新旧两个对应的节点很值得学习。

技术分享
/** * 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==NULL)  return head;        RandomListNode *pos1 = head, *pos2 = head->next;        while(pos1!=NULL) {            pos1->next = new RandomListNode(pos1->label);            pos1->next->next = pos2;            pos1 = pos2;            if(pos2!=NULL)                pos2 = pos2->next;        }        pos1 = head;        pos2 = head->next;        while(pos1!=NULL) {            if(pos1->random==NULL)                pos2->random==NULL;            else                pos2->random = pos1->random->next;            pos1 = pos2->next;            if(pos2->next!=NULL)                pos2 = pos2->next->next;        }        RandomListNode *res = head->next;        pos1 = head;        pos2 = res;        while(pos2->next!=NULL) {            pos1->next = pos2->next;            pos1 = pos2->next;            pos2->next = pos1->next;            pos2 = pos1->next;        }        pos1->next = NULL;        pos2->next = NULL;        return res;    }};
View Code

 

[leetcode] Copy List with Random Pointer