- 描述
A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
- 思路
由于有了一个随机的指针,因此这个单向链表有点像图,思路跟克隆一个图很相近,使用一个字典集合保存已经克隆的节点(key为被克隆节点的hash值,值为已克隆节点),使用递归进行克隆,每次克隆前判断是否该节点已经克隆,如果已经克隆,则取出该节点。 - 代码(c#)
public RandomListNode CopyRandomList(RandomListNode head)
{
Dictionary<int, RandomListNode> dictionary = new Dictionary<int, RandomListNode>();//保存已经克隆的节点
return CopyRandomList(head, dictionary);
}
public RandomListNode CopyRandomList(RandomListNode head, Dictionary<int, RandomListNode> dictionary)
{
if (head == null) return head;
int key = head.GetHashCode();
RandomListNode randomListNode = CopyOne(head,dictionary);//创建或取出已经克隆的节点
if (head.random != null)
{
randomListNode.random = CopyOne(head.random, dictionary);//创建或取出已经克隆的节点
}
randomListNode.next = CopyRandomList(head.next, dictionary);//克隆下一个节点
return randomListNode;
}
public RandomListNode CopyOne(RandomListNode head, Dictionary<int, RandomListNode> dictionary)
{
int key = head.GetHashCode();
RandomListNode randomListNode = null;
if (dictionary.ContainsKey(key))
{
randomListNode = dictionary[key];
}
else
{
randomListNode = new RandomListNode(head.label);
dictionary[key] = randomListNode;
}
return randomListNode;
}