深拷贝应该正好由 n 个 全新 节点组成,其中每个新节点的值都设为其对应的原节点的值。新节点的 next 指针和 random 指针也都应指向复制链表中的新节点,并使原链表和复制链表中的这些指针能够表示相同的链表状态。复制链表中的指针都不应指向原链表中的节点 。
class Solution {
public Node copyRandomList(Node head) {
if(head==null){
return null;
}
//使用HashMap方法构造映射 原节点,新节点
Map<Node,Node> map=new HashMap();
Node temp=head; //操作他
while(temp!=null){
Node clone=new Node(temp.val,null,null);//构建新节点 下一个节点是空 random也是空
//构建新节点映射
map.put(temp,clone);//旧街点 新节点
temp=temp.next;
}
//构建新节点的random 和 next
temp=head;//恢复到初始位置
while(temp!=null){
//新节点的next= 新节点的下一个节点
map.get(temp).next=map.get(temp.next);
map.get(temp).random=map.get(temp.random);
temp=temp.next;
}
//返回新节点
return map.get(head);
}
}