有一个长度为n的链表,每个结点中额外包含一个随机指针random,该指针可以指向链表中任意节点或者空NULL,请构造这个链表的深拷贝,即开辟同样的一份全新的链表空间,复制该链表构造
没有random指针的情况下,对于链表而言,逻辑结构是连续的,那么直接进行拷贝即可,但是现在结点中存在随机指针random,我们无法简单地通过一个原链表的循环来开辟新空间链接新链表,那么这里就有一种思路:
我们将每个拷贝结点先链接到原结点的后面,然后就能够链接拷贝节点间的random关系,最后断开与原结点的链接,返回拷贝的链表指针即可。
第一步---拷贝节点置于原结点后
struct Node* cur = head;
//第一步---拷贝结点到原链表每个结点之后
while (cur)
{
struct Node* next = cur->next;
struct Node* copy = (struct Node*)malloc(sizeof(struct Node));
cur->next = copy;
copy->next = next;
cur = next;
}
第二步---拷贝结点random指针赋值
//第二步---拷贝节点的random赋值
cur = head;
while (cur)
{
struct Node* copy = cur->next;
struct Node* next = copy->next;
if (cur->random == NULL)
copy->random = NULL;
else
{
copy->random = cur->random->next;
}
cur = next;
}
第三步---断开拷贝结点与原结点的连接,链接在新链表copyhead中(尾插)
//第三步---断开拷贝结点,依次尾插到copyhead并返回,重新链接原链表
cur = head;
struct Node* copyhead = NULL, * tail = copyhead;
while (cur)
{
struct Node* copy = cur->next;
struct Node* next = copy->next;
if (copyhead == NULL)
copyhead = tail = copy;
else
{
tail->next = copy;
tail = tail->next;
}
cur->next = next;//重新连接原链表
cur = next;
}
return copyhead;