0 题目
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
1 分析
也就是说这个链表,每个节点除了指向下一个节点的指针,还额外带了一个指向任意节点的指针。
如果先复制出一份只含有next指针的链表,然后再进行额外指针的赋值,那么复杂度应该是O(n^2)
因此,先原位复制一份ABC链表,复制为AABBCC
然后,将复制的链表的额外指针,指向下一个节点。
再拆分链表。
RandomListNode *Clone(RandomListNode *pHead)
{
// 提前返回
if (pHead == nullptr)
{
return nullptr;
}
RandomListNode *cur = pHead;
// 复制,ABC变为AABBCC
while (cur != nullptr)
{
RandomListNode *tmp_for_next = cur->next;
// 这里可以不用拷贝 random
cur->next = new RandomListNode(cur->label);
cur->next->next = tmp_for_next;
cur = tmp_for_next;
}
// 改变 random
cur = pHead;
while (cur != nullptr)
{
if (cur->random != nullptr)
{
cur->next->random = cur->random->next;
}
cur = cur->next->next;
}
// 拆分
RandomListNode* head_copy=pHead->next;
RandomListNode *tmp;
cur = pHead;
while (cur->next != nullptr)
{
tmp = cur->next;
cur->next = cur->next->next;
cur = tmp;
}
return head_copy;
}