剑指Offer第十六题:复杂链表的复制
题目描述
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)。
题目分析
ps:这个题很尴尬,刚开始我是用递归做,但是发现无论怎么样都没有搞出来,主要原因是,这里的random是指向的节点是链表内还是链表外呢,最后我去使用了HashMap.
递归思路(假设random指向的是链表内的):用一个节点来记录头结点,然后根据赋值,寻找下一个。
HashMap:使用哈希表的Key-Value键对,进行复制,然后直接找到pHead就可以了。
源代码
1 public class Solution666 { 2 RandomListNode newHead=null; 3 public RandomListNode Clone(RandomListNode pHead) 4 { 5 if(pHead==null) 6 return null; 7 RandomListNode node=new RandomListNode(pHead.label); 8 if(pHead.next==null&&pHead.random==null){ 9 return pHead; 10 } 11 if(newHead==null) { 12 newHead=node; 13 } 14 node.next=pHead.next; 15 node.random=pHead.random; 16 node.next=Clone(pHead.next); 17 return newHead; 18 19 } 20 }
1 public RandomListNode Clone(RandomListNode pHead) { 2 HashMap<RandomListNode, RandomListNode> hashMap=new HashMap<RandomListNode,RandomListNode>(); 3 RandomListNode node=pHead; 4 while(node!=null) { 5 hashMap.put(node,new RandomListNode(node.label)); 6 node=node.next; 7 } 8 node=pHead; 9 while(node!=null) { 10 hashMap.get(node).next=hashMap.get(node.next); 11 node=node.next; 12 } 13 node=pHead; 14 while(node!=null) { 15 hashMap.get(node).random=hashMap.get(node.random); 16 node=node.next; 17 } 18 return hashMap.get(pHead); 19 20 }
这个算法我也不是弄得太明白,思路很乱,希望有个大佬给我指点指点。