解决思路:
①节点value 的复制,只需要 new Node(value)即可
②节点指针的复制,(next,random)的复制
1.通过HashMap 存储师徒之间的关系,遍历师傅,创建相同节点的徒弟。
2. 再次遍历,需要处理师徒之间的关系
/*
// Definition for a Node.
class Node {
int val;
Node next;
Node random;
public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
}
*/
class Solution {
public Node copyRandomList(Node head) {
HashMap<Node,Node> hashMap=new HashMap<>();
Node cur=head;
while(cur!=null){
hashMap.put(cur,new Node(cur.val));
cur=cur.next;
}
cur=head;
while(cur!=null){
hashMap.get(cur).next=hashMap.get(cur.next);
hashMap.get(cur).random=hashMap.get(cur.random);
cur=cur.next;
}
return hashMap.get(head);
}
}