题目描述
请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。
示例1

输入
head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
返回值
[[7,null],[13,0],[11,4],[10,2],[1,0]]
示例2

输入
head = [[1,1],[2,1]]
返回值
[[1,1],[2,1]]
示例3

输入
head = [[3,null],[3,0],[3,null]]
返回值
[[3,null],[3,0],[3,null]]
示例4
输入
head = []
返回值
[]
解题思路
- 不能直接返回 Node 的地址,题目要求是深拷贝而不是浅拷贝。
- 在 Node 没有 random 属性的情况下,我们可以很轻松地直接用遍历的方式,用双指针进行深拷贝,前一个指针的 next 就是下一个指针指向的对象的复制件。但多出来一个 random,使得我们使用双指针时无法得知 random 指向的位置,贸然深度拷贝 random,有可能会复制出无限多的同样的对象。
- 用 Map 简历 (原对象,新对象)的映射表,当要查找当前 Node 的 random 时,会直接找到 Map 中映射的对象,这样即使指向 random,也不会拷贝出无限多份。
Java代码实现
/**
// 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 {
public Node copyRandomList(Node head) {
HashMap<Node, Node> map = new HashMap<Node, Node>();
Node cur = head;
while (cur != null) {
map.put(cur, new Node(cur.val));
cur = cur.next;
}
cur = head;
while (cur != null) {
map.get(cur).next = map.get(cur.next);
map.get(cur).random = map.get(cur.random);
cur = cur.next;
}
return map.get(head);
}
} 
京公网安备 11010502036488号