题目描述
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
struct RandomListNode {
int label;
struct RandomListNode *next, *random;
RandomListNode(int x): label(x), next(NULL), random(NULL) {}
};
解题思路
1 通用分治算法
第一步,在每个节点的后面插入复制的节点。
第二步,对复制节点的 random 链接进行赋值。
第三步,拆分。
/*
struct RandomListNode {
int label;
struct RandomListNode *next, *random;
RandomListNode(int x) :
label(x), next(NULL), random(NULL) {
}
};
*/
class Solution {
public:
//[1]复制结点,插入到原结点后方
RandomListNode* Clone(RandomListNode* pHead) {
if(!pHead) return nullptr;
CloneNodes(pHead);
ConnectRandom(pHead);
return ReconnectNodes(pHead);
}
//[2]还原新结点的random指针
void CloneNodes(RandomListNode* pHead) {
auto pNode = pHead;
while(pNode) {
auto pClone = new RandomListNode(pNode->label);
pClone->next = pNode->next;
pNode->next = pClone;
pNode = pClone->next;
}
}
//[3]拆分
void ConnectRandom(RandomListNode* pHead) {
auto pNode = pHead;
while(pNode) {
auto pClone = pNode->next;
if(pNode->random) pClone->random = pNode->random->next;
pNode = pClone->next;
}
}
RandomListNode* ReconnectNodes(RandomListNode* pHead) {
auto pNode = pHead, pCloneHead = pNode->next, pClone = pCloneHead;
pNode->next = pClone->next;
pNode = pNode->next;
while(pNode) {
pClone->next = pNode->next;
pClone = pClone->next;
pNode->next = pClone->next;
pNode = pNode->next;
}
return pCloneHead;
}
};
2 超强递归大法
以空间换时间
class Solution {
private:
unordered_map<RandomListNode*, RandomListNode*> map;
public:
RandomListNode* Clone(RandomListNode* pHead) {
if(!pHead) return nullptr;
if(map.find(pHead) != map.end()) return map[pHead];
RandomListNode* res = new RandomListNode(pHead->label);
map[pHead] = res;
res->next = Clone(pHead->next);
res->random = Clone(pHead->random);
return res;
}
};