题目描述:
思路:利用哈希表的查询特点,考虑构建 原链表节点 和 新链表对应节点 的键值对映射关系,再遍历构建新链表各节点的 next
和 random
引用指向即可。
代码如下:
class Solution {
public Node copyRandomList(Node head) {
if(head==null){
return null;
}
Node cur=head;
HashMap<Node, Node> map = new HashMap<Node, Node>();
while (cur!=null){
map.put(cur,new Node(cur.val));
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);
}