![](https://i-blog.csdnimg.cn/blog_migrate/af5be3de8cb4ef0ea4b5e9c8f9efe806.png)
思路:链表的深拷贝可以利用到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);
}
|