该链表每个节点除了有值和下一个节点的指针,还有随机指针,其指向链表中任意的元素,也有可能为null。
python代码:
# -*- coding:utf-8 -*-
# class RandomListNode:
# def __init__(self, x):
# self.label = x
# self.next = None
# self.random = None
class Solution:
# 返回 RandomListNode
def Clone(self, pHead):
# write code here
if not pHead:
return
newHead = RandomListNode(pHead.label)
newHead.random = pHead.random
newHead.next = self.Clone(pHead.next)
return newHead
利用递归实现
C++代码:
/*
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 nullptr;
}
RandomListNode* res = pHead;
cloneLinkList(res);
coloneRandomList(res);
return dipartion(res);
}
void cloneLinkList(RandomListNode* pHead){
RandomListNode* pNode = pHead;
while(pNode){
RandomListNode* pClone = new RandomListNode(pNode->label);
pClone->next = pNode->next;
pClone->random = nullptr;
pNode->next = pClone;
pNode = pClone->next;
}
}
void coloneRandomList(RandomListNode* pHead){
RandomListNode* pNode = pHead;
while(pNode){
RandomListNode* pCloned = pNode->next;
if(pNode->random){
pCloned->random = pNode->random->next;
}
pNode = pCloned->next;
}
}
RandomListNode* dipartion(RandomListNode* pHead){
RandomListNode* pNode = pHead;
RandomListNode* pClonedHead = nullptr;
RandomListNode* pClonedNode = nullptr;
if(pNode){
pClonedHead = pClonedNode = pNode->next;
pNode->next = pClonedNode->next;
pNode = pNode->next;
}
while(pNode){
pClonedNode->next = pNode->next;
pClonedNode = pClonedNode->next;
pNode->next = pClonedNode->next;
pNode = pNode->next;
}
return pClonedHead;
}
};
第一步,复制原始链表任意节点,并把复制后的节点链接到原始节点的后面。
第二步,设置复制出来的节点的随机指针。
第三步,将两个链表分开。
代码地址