题解 | #复杂链表的复制#
复杂链表的复制
http://www.nowcoder.com/practice/f836b2c43afc4b35ad6adc41ec941dba
/*
public class RandomListNode
{
public int label;
public RandomListNode next, random;
public RandomListNode (int x)
{
this.label = x;
}
}*/
using System.Collections.Generic;
class Solution
{
public RandomListNode Clone(RandomListNode pHead)
{
// write code here
if (pHead == null) return pHead;
Dictionary<RandomListNode, RandomListNode> dic = new Dictionary<RandomListNode, RandomListNode>();
RandomListNode newHead = new RandomListNode(0);
RandomListNode iter = pHead;
RandomListNode iterNew = newHead;
while(iter!=null){
RandomListNode tmp = new RandomListNode(iter.label);
iterNew.next = tmp;
dic[iter] = tmp;
iter = iter.next;
iterNew = iterNew.next;
}
foreach(RandomListNode node in dic.Keys){
dic[node].random = node.random==null? null : dic[node.random];
}
return newHead.next;
}
}
public class RandomListNode
{
public int label;
public RandomListNode next, random;
public RandomListNode (int x)
{
this.label = x;
}
}*/
using System.Collections.Generic;
class Solution
{
public RandomListNode Clone(RandomListNode pHead)
{
// write code here
if (pHead == null) return pHead;
Dictionary<RandomListNode, RandomListNode> dic = new Dictionary<RandomListNode, RandomListNode>();
RandomListNode newHead = new RandomListNode(0);
RandomListNode iter = pHead;
RandomListNode iterNew = newHead;
while(iter!=null){
RandomListNode tmp = new RandomListNode(iter.label);
iterNew.next = tmp;
dic[iter] = tmp;
iter = iter.next;
iterNew = iterNew.next;
}
foreach(RandomListNode node in dic.Keys){
dic[node].random = node.random==null? null : dic[node.random];
}
return newHead.next;
}
}