输入一个复杂链表
每个节点 节点值,两个指针,一个指向下一个节点, 另一个特殊指针指向任意一个节点或者NULL
现给定这样一个链表,返回复制后的链表
基本思路:对原链表每一个节点之后插入一个相等的节点,同时有 copy->random=be_copied->random->next
代码实现:
RandomListNode* Clone(RandomListNode* pHead)
{
if(pHead==NULL)
return NULL;
//在原先链表每个节点之后插入一个一模一样的节点
RandomListNode* temp=pHead;
while(temp!=NULL)
{
RandomListNode* copy=new RandomListNode(temp->label);//复制一个节点
copy->next=temp->next;
temp->next=copy;
temp=copy->next;
}
//对于新插入的每个节点,其random指针 是其前一个节点random指向的节点的下一个(平行关系)
temp=pHead;
while(temp!=NULL)
{
RandomListNode* node=temp->next;
if(temp->random)
node->random=temp->random->next;
temp=node->next;
}
//完成之后,将原先链表拆分
temp=pHead;
RandomListNode* res=pHead->next;
RandomListNode* node;
while(temp->next!=NULL)
{
node=temp->next;
temp->next=node->next;
temp=node;
}
return res;
}