![]()
![]()
1 /*
2 class Node {
3 int val;
4 Node next;
5 Node random;
6
7 public Node(int val) {
8 this.val = val;
9 this.next = null;
10 this.random = null;
11 }
12 }
13 */
14
15 class Solution {
16 public Node copyRandomList(Node head) {
17 // 判空入参
18 if(head == null){
19 return null;
20 }
21 // 申请临时指针
22 Node cur = head;
23 // 申请HashMap用于存储复制节点
24 HashMap<Node,Node> map = new HashMap<>();
25 // 拷贝复制节点到HashMap
26 while(cur != null){
27 map.put(cur,new Node(cur.val));
28 cur = cur.next;
29 }
30 // 针对新节点的next指针和random指针进行赋值
31 cur=head;
32 while(cur!=null){
33 map.get(cur).next=map.get(cur.next);
34 map.get(cur).random=map.get(cur.random);
35 cur=cur.next;
36 }
37 // 返回结果
38 return map.get(head);
39 }
40 }