又是一个深拷贝问题,和“Graph Clone"一样,用map,递归:
Map<RandomListNode, RandomListNode> map = new HashMap<>();
public RandomListNode copyRandomList(RandomListNode head) {
if (head == null) {
return null;
}
if (map.containsKey(head)) {
return map.get(head);
}
RandomListNode result = new RandomListNode(head.label);
map.put(head, result);
result.next = copyRandomList(head.next);
result.random = copyRandomList(head.random);
return result;
}