难点在于random的指向,因为它并不是通过值来区分每一个结点的(有值相同的两个不同的节点)
如果能想到使用Map的映射规则,那么就很简单了
第一遍构建next 链表
第二遍通过 Map 中的映射,构建 random
class Solution {
public Node copyRandomList(Node head) {
if(head == null)
return null;
Map<Node,Node> map = new HashMap<>();
Node n = new Node(head.val);
map.put(head,n);
Node t1 = head.next, t2 = n;
while(t1 != null){
t2.next = new Node(t1.val);
map.put(t1,t2.next);
t2 = t2.next;
t1 = t1.next;
}
map.put(null,null);
t1 = head;
t2 = n;
while(t1 != null){
t2.random = map.get(t1.random);
t2 = t2.next;
t1 = t1.next;
}
return n;
}
}