描述
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针random指向一个随机节点),请对此链表进行深拷贝,并返回拷贝后的头结点。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
解法
第一步,在每个节点的后面插入复制的节点;
第二步,对复制节点的 random 链接进行赋值;
第三步,拆分
/*
struct RandomListNode {
int label;
struct RandomListNode *next, *random;
RandomListNode(int x) :
label(x), next(NULL), random(NULL) {
}
};
*/
class Solution {
public:
RandomListNode* Clone(RandomListNode* pHead) {
if(pHead == nullptr) return pHead;
//第一步,在每个节点的后面插入复制的节点。
RandomListNode* cur = pHead;
while(cur)
{
RandomListNode* copyNode = new RandomListNode(cur->label);
copyNode->next = cur->next;
cur->next = copyNode;
cur = copyNode->next;
}
//第二步,对复制节点的 random 链接进行赋值。
cur = pHead;
while(cur)
{
RandomListNode* copyNode = cur->next;
if(cur->random != nullptr)
{
copyNode->random = cur->random->next;
}
cur = copyNode->next;
}
//第三步,拆分。
RandomListNode* newNode = pHead->next; //指向copy链表的首元素
RandomListNode* next = nullptr;
cur = pHead;
while(cur->next)
{
next = cur->next;
cur->next = next->next;
cur = next;
}
// cur->next = nullptr;
// next->next = nullptr;
return newNode;
}
};