题目描述
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
思路
第一步:复制节点,将新创建的节点N’接到N的后面。
第二步:复制random指针
第三步:拆分链表
代码
class Solution {
public:
RandomListNode* Clone(RandomListNode* pHead)
{
if (pHead == nullptr) return nullptr;
RandomListNode *p = pHead;
//在每个节点A后复制一个相同的节点A',A->B->C->NULL, A->A'->B->B'->C->C'->NULL
while (p != nullptr)
{
RandomListNode *temp = new RandomListNode(p -> label);
temp -> next = p -> next;
p -> next = temp;
p = temp -> next;
}
//复制random指针,A'random指向的一定是Arandom指向的下一个元素。
p = pHead;
while (p != nullptr)
{
if (p -> random != nullptr)
p -> next -> random = p -> random -> next;
p = p -> next -> next;
}
//将链表拆分,A->A'->B->B'->C->C'->NULL,A->B->C->NULL and A'->B'->C'->NULL
p = pHead;
RandomListNode *myHead = p -> next;
RandomListNode *q = myHead;
while (p != nullptr)
{
p -> next = q -> next;
if (q -> next != nullptr)
q -> next = p -> next -> next;
p = p -> next;
q = q -> next;
}
return myHead;
}
};
参考:
https://www.cnblogs.com/silentteller/p/11931355.html