题目来源:力扣
题目:
方法:
1.复制节点,并将其插入在原节点的后面
2.控制新节点的random指针
3.将新节点拿下来尾插,产生新链表
struct Node* copyRandomList(struct Node* head)
{
if(head == NULL)
return NULL;
//1.复制节点,并将其插入在原节点的后面
struct Node* pcur = head;
while(pcur)
{
//复制节点
struct Node* copy = (struct Node*)malloc(sizeof(struct Node));
copy->val = pcur->val;
//新节点插入在原节点之后
copy->next = pcur->next;
pcur->next = copy;
//pcur往后移动
pcur = copy->next;
}
//2.控制新节点的random指针
pcur = head;
struct Node* copy = pcur->next;
while(pcur)
{
if(pcur->random == NULL)
{
copy->random = NULL;
}
else
{
copy->random = pcur->random->next;
}
pcur = copy->next;
if(pcur)
{
copy = pcur->next;
}
}
//3.将新节点拿下来尾插,产生新链表
pcur = head;
copy = pcur->next;
struct Node* copyhead = NULL;
struct Node* copytail = NULL;
while(pcur)
{
if(copyhead == NULL)
{
copyhead = copytail = copy;
}
else
{
copytail->next = copy;
copytail = copy;
}
//顺带恢复一下原链表
pcur->next = copy->next;
//pcur,copy指针往后走
pcur = copy->next;
if(pcur)
{
copy = pcur->next;
}
}
return copyhead;
}