复制带随机值指针的链表
题目:
- 第一步
遍历插入每个结点的拷贝结点
- 第二步
更新copy结点的random的值
==》如此循环往下知道cur=null
一.常规
struct Node* copyRandomList(struct Node* head) {
struct Node* cur=head;
struct Node* next=NULL;
struct Node* copy=NULL;
//1.首先遍历链表在每两个节点中间插入节点的拷贝
while(cur)
{
//复制链接
next=cur->next;
copy=(struct Node*)malloc(sizeof(struct Node));
copy->val=cur->val;
cur->next=copy;
copy->next=next;
//迭代循环更新cur
cur=next;
}
//2.更新copy结点的random的值
cur=head;
while(cur)
{
copy=cur->next;
if(cur->random==NULL)
{
copy->random=NULL;
}
else
{
copy->random=cur->random->next;
}
//迭代
cur=cur->next->next;
}
//3.把拷贝的结点解下来
struct Node* copyhead=NULL;//作copy链表的哨兵
struct Node* copytail=NULL;//记录copy链表的为结点位置
cur=head;
while(cur)
{
copy=cur->next;
next=copy->next;
if(copytail==NULL)
{
copyhead=copytail=copy;
}
else
{
copytail->next=copy;
copytail=copytail->next;
}
cur->next=next;
cur=next;
}
return copyhead;
}
二.用带哨兵的
```c
struct Node* copyRandomList(struct Node* head) {
struct Node* cur=head;
struct Node* next=NULL;
struct Node* copy=NULL;
//1.首先遍历链表在每两个节点中间插入节点的拷贝
while(cur)
{
//复制链接
next=cur->next;
copy=(struct Node*)malloc(sizeof(struct Node));
copy->val=cur->val;
cur->next=copy;
copy->next=next;
//迭代循环更新cur
cur=next;
}
//2.更新copy结点的random的值
cur=head;
while(cur)
{
copy=cur->next;
if(cur->random==NULL)
{
copy->random=NULL;
}
else
{
copy->random=cur->random->next;
}
//迭代
cur=cur->next->next;
}
//3.把拷贝的结点解下来
struct Node* copyhead=(struct Node*)malloc(sizeof(struct Node));//作copy链表的哨兵
//或者初始化哨兵结点,因为如果为空链表,三个循环都不会进去,
//如果不初始化,最后返回copyhead->next,地址是随机的,是野指针
//copy->next=null;
struct Node* copytail=copyhead;//记录copy链表的为结点位置
cur=head;
while(cur)
{
copy=cur->next;
next=copy->next;
copytail->next=copy;//尾插到哨兵后面
copytail=copytail->next;//更新尾指针
//恢复原链表链接
cur->next=next;
//迭代
cur=next;
}
// copytail->next=NULL;
return copyhead->next;
}