https://leetcode.com/problems/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,两次遍历,第一次构造出新的链表,并构造map映射,第二次修改新链表中的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) {
static int fast_io = []() { std::ios::sync_with_stdio(false); cin.tie(nullptr); return 0; }();
unordered_map<RandomListNode*, RandomListNode*> M;
RandomListNode *new_head = new RandomListNode(0);
RandomListNode *new_cur = new_head;
RandomListNode *cur = head;
while(cur != NULL){
new_cur->next = new RandomListNode(cur->label);
M[cur] = new_cur->next;
new_cur = new_cur->next;
cur = cur->next;
}
cur = head;
new_cur = new_head->next;
while(cur != NULL){
if(cur->random != NULL){
new_cur->random = M[cur->random];
}
new_cur = new_cur->next;
cur = cur->next;
}
return new_head->next;
}
};
但是看到了别人的更酷的方法,使用三次遍历,但是可以不使用map结构,减少了维护的开销和对复杂数据结构的依赖。
由于没有map,我们就需要新的方法来维护节点到它的拷贝的映射关系。
第一次遍历同样是复制链表,维护映射,但是维护的方式是将节点的拷贝作为它的后继直接插入在原始链表中。
第二次遍历修改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) {
RandomListNode *new_head = new RandomListNode(0);
for(RandomListNode *cur = head; cur != NULL; cur = cur->next->next){
RandomListNode *copy = new RandomListNode(cur->label);
copy->next = cur->next;
cur->next = copy;
}
for(RandomListNode *cur = head; cur != NULL; cur = cur->next->next){
if(cur->random != NULL){
cur->next->random = cur->random->next;
}
}
for(RandomListNode *cur = head, *new_cur = new_head; cur != NULL; cur = cur->next, new_cur = new_cur->next){
new_cur->next = cur->next;
cur->next = cur->next->next;
}
return new_head->next;
}
};