这个一个人链表的深度拷贝
old链表为
第一步
在每一个old节点的后面加上新的copy节点 ,形成新的链表如下图所示
copy节点中的random指针指向 它要复制的old节点 next指针指向 要复制节点中的old节点中的next
第二步
更新copy节点中random指针值
copy节点中的random指针现在指向 它要copy的节点
如果copy->random->random=NULL 则 copy->random=NULL
否则 copy->random=copy->random->random->next;
第三步
更新整个链表的Next指针 恢复原来的状态
只要从前向后遍历
temp->next=temp->next->next;
就把原来的old 链表和 copy链表分开了
class Solution {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
if(!head)
return NULL;
RandomListNode *temp=head;
RandomListNode *returnptr=NULL;
while(temp)//将copy点加入到old点的后面
{
RandomListNode *copy=new RandomListNode(temp->label);
if(!returnptr)
returnptr=copy;
copy->next=temp->next;
temp->next=copy;copy->random=temp;
temp=temp->next->next;
}
temp=returnptr;
while(temp)//更新copy点random指针的值
{
if(temp->random->random==NULL)
temp->random=NULL;
else
temp->random=temp->random->random->next;
if(temp->next==NULL)
break;
temp=temp->next->next;
}
temp=head;
while(temp->next!=NULL)//更新 old节点还有 copy节点的next指针
{
RandomListNode *a=temp->next;
temp->next=temp->next->next;
temp=a;
}
return returnptr;
}
};