题目分析:
这题要实现深拷贝,并不是简单的new,还要将next,random的对应结点按对应位置存储,因此需要一个映射关系,将原链表和每一次new出来的结点映射,这样遍历原链表的next或random(key),就能对应到映射表里面的next或random(value)
图解:
代码演示:
public Node copyRandomList(Node head) {
Map<Node,Node> map=new HashMap<>();
Node cur=head;
//遍历链表建立映射关系
while(cur!=null){
Node node=new Node(cur.val);//新链表的每个结点
map.put(cur,node);
cur=cur.next;
}
//再次遍历链表给每个结点实现深拷贝
cur=head;
while(cur!=null){
map.get(cur).next=map.get(cur.next);
map.get(cur).random=map.get(cur.random);
cur=cur.next;
}
return map.get(head);
}