思路:链表的深拷贝可以利用到HashMap,进行两次遍历,第一次进行赋初始值,第二遍对random和next值进行初始化
|
public Node copyRandomList(Node head) {
if(head==null)return null;
HashMap<Node ,Node>map=new HashMap<>();
Node temp=head;
while(temp!=null){
map.put(temp,new Node(temp.val));
temp=temp.next;
}
temp=head;
while (temp!=null){
map.get(temp).next=map.get(temp.next);
map.get(temp).random=map.get(temp.random);
temp=temp.next;
}
return map.get(head);
}
|