题目描述
给你一个长度为 n 的链表,每个节点包含一个额外增加的随机指针 random ,该指针可以指向链表中的任何节点或空节点。
构造这个链表的 深拷贝。 深拷贝应该正好由 n 个 全新 节点组成,其中每个新节点的值都设为其对应的原节点的值。新节点的 next 指针和 random 指针也都应指向复制链表中的新节点,并使原链表和复制链表中的这些指针能够表示相同的链表状态。复制链表中的指针都不应指向原链表中的节点 。
解题思路
1.拷贝原链表的每一个结点,链接在原结点后
2.处理拷贝结点的random
copy->random=cur->random->next;
3.把拷贝结点从原链表里拆解出来
注意:每一次循环遍历变量的初始化和迭代条件
struct Node* copyRandomList(struct Node* head) {
if (head == NULL)
return NULL;
//1.拷贝原链表的每一个结点,链接到原结点后面
// 11 22 33
//1 2 3
struct Node*cur = head;//初始化
while (cur)
{
struct Node*copy = (struct Node*)malloc(sizeof(struct Node));
copy->next = NULL;
copy->random = NULL;
copy->val = cur->val;
struct Node*next = cur->next;//初始化
copy->next = cur->next;
cur->next = copy;
cur = next;//迭代
}
//2.处理拷贝结点的random
cur = head;//初始化
while (cur)
{
struct Node*copy = cur->next;//初始化
if (cur->random)
copy->random = cur->random->next;
else
copy->random = NULL;
cur = cur->next->next;//迭代
}
//3.把拷贝结点从原链表中拆解出来-3个指针
// copy
//cur next
cur = head;//初始化
struct Node*copyhead = head->next;//保存copyhead
while (cur)
{
struct Node*copy = cur->next;//初始化
struct Node*next = copy->next;//初始化
cur->next = next;//断开
if (next)
copy->next = next->next;//新链表连下一个结点
else
copy->next = NULL;//置空
cur = next;//迭代
}
return copyhead;
}