问题
例子
思路
直接遍历结点的话,因为random是随机的,有没有创建不知道,所以使用辅助map,旧结点,新结点【遍历结点,复制一份,并放在map中与原结点进行映射】,则原结点之间的映射关系,就是新节点之间的映射关系
-
方法1
$$$$
-
方法2
$$$$
代码
//方法1
/*
// 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) {
if(head==null) return null;
Map<Node,Node> map = new HashMap<>();
Node node = head;
while(node!=null) {
map.put(node,new Node(node.val));
node = node.next;
}
node=head;
while(node!=null) {
map.get(node).next = map.get(node.next);
map.get(node).random = map.get(node.random);
node=node.next;
}
return map.get(head);
}
}
//方法2