给你一个长度为 n 的链表,每个节点包含一个额外增加的随机指针 random ,该指针可以指向链表中的任何节点或空节点。
构造这个链表的 深拷贝。 深拷贝应该正好由 n 个 全新 节点组成,其中每个新节点的值都设为其对应的原节点的值。新节点的 next 指针和 random 指针也都应指向复制链表中的新节点,并使原链表和复制链表中的这些指针能够表示相同的链表状态。复制链表中的指针都不应指向原链表中的节点 。
例如,如果原链表中有 X 和 Y 两个节点,其中 X.random --> Y 。那么在复制链表中对应的两个节点 x 和 y ,同样有 x.random --> y 。
返回复制链表的头节点。
用一个由 n 个节点组成的链表来表示输入/输出中的链表。每个节点用一个 [val, random_index] 表示:
val:一个表示 Node.val 的整数。
random_index:随机指针指向的节点索引(范围从 0 到 n-1);如果不指向任何节点,则为 null 。
你的代码 只 接受原链表的头节点 head 作为传入参数。
解题思路:
这道题是将指针复制下来关键点就是这里的random这个指针,我们考虑的是这个random指向的下标。
第一步开辟新的一个结点放在每一个指针的后面
//第一步先将每一个结点拷贝下来
struct Node* cur=head;
while(cur)
{
struct Node* copy=(struct Node*)malloc(sizeof(struct Node));
struct Node* tail=cur->next;
copy->val=cur->val;//拷贝的是数值并不是地址
copy->next=tail;
cur->next=copy;
cur=tail;
}
第二步找random的位置,原链表里面的random是随机指向的,可以找到规律,原链表random指向的下一个坐标就是原来指向的数值
//第二部将节点的random找出来指向当前结点的下一个
cur=head;
while(cur)
{
struct Node* copytail=cur->next;
if(cur->random==NULL)
{
copytail->random=NULL;
}
else
{
copytail->random=cur->random->next;
}
cur=cur->next->next;
}
第三步,需要将复制的代码解下来
struct Node* copyhead=NULL;
struct Node* copytail=NULL;
cur=head;
//第三步将结点重新
while(cur)
{
struct Node* copy=cur->next;
struct Node* next=cur->next->next;
cur->next=next;
if(copytail==NULL)
{
copyhead=copytail=copy;
}
else
{
copytail->next=copy;
copytail=copytail->next;
}
cur=next;
}
完整代码
struct Node* copyRandomList(struct Node* head)
{
//第一步先将每一个结点拷贝下来
struct Node* cur=head;
while(cur)
{
struct Node* copy=(struct Node*)malloc(sizeof(struct Node));
struct Node* tail=cur->next;
copy->val=cur->val;//拷贝的是数值并不是地址
copy->next=tail;
cur->next=copy;
cur=tail;
}
//第二部将节点的random找出来指向当前结点的下一个
cur=head;
while(cur)
{
struct Node* copytail=cur->next;
if(cur->random==NULL)
{
copytail->random=NULL;
}
else
{
copytail->random=cur->random->next;
}
cur=cur->next->next;
}
struct Node* copyhead=NULL;
struct Node* copytail=NULL;
cur=head;
//第三步将结点重新
while(cur)
{
struct Node* copy=cur->next;
struct Node* next=cur->next->next;
cur->next=next;
if(copytail==NULL)
{
copyhead=copytail=copy;
}
else
{
copytail->next=copy;
copytail=copytail->next;
}
cur=next;
}
return copyhead;
}