思路是建立hashMap,建立一一对应关系,这样就能实现 random的指针。
public class Solution {
public Node copyRandomList(Node head) {
// 这是一个复杂的树结构
// 问题的关键是建立,新创建的树和之前树的一一对应关系
if (head == null) {
return null;
}
// 原树结构不为空
Node newHead = new Node(head.val);
Node tmp = newHead;
HashMap<Node, Node> map = new HashMap<>();
map.put(head, newHead);
while (head.next != null) {
head = head.next;
tmp.next = new Node(head.val);
tmp = tmp.next;
map.put(head, tmp);
}
// 复制了所有的结点
Set<Node> set = map.keySet();
for (Node node : set) {
// 结点的random结点是对应的旧结点指向的random所对应的新节点
map.get(node).random = map.get(node.random);
}
return newHead;
}
}