https://leetcode-cn.com/problems/fu-za-lian-biao-de-fu-zhi-lcof/
代码 (hash表
/*
// Definition for a Node.
class Node {
int val;
Node next;
Node random;
public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
}
*/
class Solution {
//用哈希表记录每一个节点对应新节点的创建情况
Map<Node, Node> cachedNode = new HashMap<Node, Node>();
public Node copyRandomList(Node head) {
//判断为空拦截
if (head == null) {
return null;
}
//为了防止重复拷贝,需要首先检查当前节点是否被拷贝过
if (!cachedNode.containsKey(head)) {
//拷贝新节点,放入Map
Node headNew = new Node(head.val);
cachedNode.put(head, headNew);
//当拷贝完成,回溯到当前层时,我们即可完成当前节点的指针赋值。
headNew.next = copyRandomList(head.next);
headNew.random = copyRandomList(head.random);
}
//如果已经拷贝过,我们可以直接从哈希表中取出拷贝后的节点的指针并返回即可。
return cachedNode.get(head);
}
}