题意:
给定一个linkedlist,同时每个node还有一个random指针。现在要求将这个list进行深度复制,即重新复制出来一个node list,然后next和random指针和原来的一样。
解决方案:
next指针进行深复制比较容易,random指针的复制就利用两个HashMap进行记录,具体就是将原来的list和新的list的对应记录一下;原来list的random指针的两个节点记录一下。最后遍历所有的random指针,新的random根据旧的random以及新list到旧list的对应,就ok了。
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
// DeFfinition for singly-linked list with a random pointer.
class RandomListNode {
int label;
RandomListNode next, random;
RandomListNode(int x) {
this.label = x;
}
};
public class Solution {
public RandomListNode copyRandomList(RandomListNode head) {
if (head == null)
return null;
HashMap<RandomListNode, RandomListNode> set = new HashMap<RandomListNode, RandomListNode>();
HashMap<RandomListNode, RandomListNode> random = new HashMap<RandomListNode, RandomListNode>();
RandomListNode neoHead = new RandomListNode(head.label);
RandomListNode tot = head, neoTot = neoHead, ran, neoRan;
while (tot != null) {
set.put(tot, neoTot);
random.put(tot, tot.random);
tot = tot.next;
if (tot == null)
break;
neoTot.next = new RandomListNode(tot.label);
neoTot = neoTot.next;
}
Iterator<RandomListNode> ite = random.keySet().iterator();
RandomListNode a, b;
while (ite.hasNext()) {
a = ite.next();
b = random.get(a);
set.get(a).random = set.get(b);
}
return neoHead;
}
}