题目:
A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
The Linked List is represented in the input/output as a list of n nodes. Each node is represented as a pair of [val, random_index]
where:
- val: an integer representing Node.val
- random_index: the index of the node (range from 0 to n-1) where random pointer points to, or null if it does not point to any node.
Constraints: - -10000 <= Node.val <= 10000
- Node.random is null or pointing to a node in the linked list.
- Number of Nodes will not exceed 1000.
解答:
注意题目中要求的是深拷贝,即新链表的每个节点必须是新new出来的,否则就只是之前旧链表的引用,而非深拷贝。
基本思路为:
- 复制给定链表中的每一个节点,将其插入到给定链表中原节点的后面。
- 复制random节点。由于新节点就在原节点的后面,因此,依次检测给定链表中的每个节点,若random不为空,则将它的下一个节点(对应新节点)的random指针指向原节点random指针所指节点的下一个节点。
- 最后再将该链表拆分成新、旧两个链表,返回新链表。
一个详细的解答如下所示:复制带有随机指针的链表
这里我们采用一种更为简便的解法
- 将原链表先全部遍历一遍,创建新节点,并在map中记录原节点与新节点的映射关系。(注意每次都必须new Node)
- 第二次遍历,添加上新节点的next和random
代码实现如下:
class Solution {
public Node copyRandomList(Node head) {
Node pre = head;
HashMap<Node, Node> map = new HashMap<>();
while(pre != null) {
map.put(pre, new Node(pre.val));
pre = pre.next;
}
pre = head;
while(pre!= null) {
map.get(pre).next = map.get(pre.next);
map.get(pre).random = map.get(pre.random);
pre = pre.next;
}
return map.get(head);
}
}