. - 力扣(LeetCode). - 备战技术面试?力扣提供海量技术面试资源,帮助你高效提升编程技能,轻松拿下世界 IT 名企 Dream Offer。https://leetcode.cn/problems/fu-za-lian-biao-de-fu-zhi-lcof/
代码实现:
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
*/
class Solution {
public:
Node* copyRandomList(Node* head) {
//1.拷贝结点连接到源节点的后面
Node*cur=head;
while(cur)
{
Node* next=cur->next;
Node* copy=new Node(cur->val);
cur->next=copy;
copy->next=next;
copy=copy->next;
cur=cur->next->next;
cur=next;//迭代遍历
}
//2.置random
cur=head;
while(cur)
{
Node* copy=cur->next;
if(cur->random==NULL) copy->random=NULL;
else copy->random=cur->random->next;
cur=cur->next->next;
}
//3.拆解拷贝链表,在链接到一起
cur=head;
Node* copyHead,*copyTail;
copyHead=copyTail=new Node(0);
while(cur)
{
Node* copy=cur->next;
Node* next=copy->next;
cur->next=next;
//尾插
copyTail->next=copy;
copyTail=copy;
cur=next;//迭代遍历
}
return copyHead->next;
}
};