题目要求
给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。要求返回这个链表的深拷贝。
思路
第一步,先在原链表每个结点的后面创建一个结点的拷贝,将值也拷贝进去,链接成一个链表。第二步,原链表的拷贝结点的随机指针等于原链表随机指针的next,将所有的随机指针拷贝进去。第三步,将一个链表拆分成两个链表。
图解
代码实现
struct Node* copyRandomList(struct Node* head) {
struct Node* cur = head;
struct Node* next = cur;
while (cur)
{
next = cur->next;
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->val = cur->val;
cur->next = node;
node->next = next;
cur = next;
}
cur = head;
while (cur)
{
if (cur->random == NULL)
{
cur->next->random = NULL;
}
else
{
cur->next->random = cur->random->next;
}
cur = cur->next->next;
}
cur = head;
struct Node* newhead = NULL;
struct Node* newtail = NULL;
while (cur)
{
struct Node* copy = cur->next;
struct Node* next = copy->next;
if (newhead == NULL)
{
newhead = newtail = copy;
}
else
{
newtail->next = copy;
newtail = copy;
}
cur->next = next;
cur = next;
}
return newhead;
}