给你一个长度为 n
的链表,每个节点包含一个额外增加的随机指针 random
,该指针可以指向链表中的任何节点或空节点。
构造这个链表的 深拷贝。 深拷贝应该正好由 n
个 全新 节点组成,其中每个新节点的值都设为其对应的原节点的值。新节点的 next
指针和 random
指针也都应指向复制链表中的新节点,并使原链表和复制链表中的这些指针能够表示相同的链表状态。复制链表中的指针都不应指向原链表中的节点 。
例如,如果原链表中有 X
和 Y
两个节点,其中 X.random --> Y
。那么在复制链表中对应的两个节点 x
和 y
,同样有 x.random --> y
。
返回复制链表的头节点。
采用hashmap的方式,将新链表节点与旧链表一一映射,然后再根据就链表的映射关系来映射新链表
- package TOP21_30;
-
- import java.util.HashMap;
- import java.util.Map;
-
- //随机链表的复制
- //给你一个长度为 n 的链表,每个节点包含一个额外增加的随机指针 random ,该指针可以指向链表中的任何节点或空节点。
- //构造这个链表的 深拷贝。 深拷贝应该正好由 n 个 全新 节点组成,其中每个新节点的值都设为其对应的原节点的值。新节点的 next 指针和 random 指针也都应指向复制链表中的新节点,并使原链表和复制链表中的这些指针能够表示相同的链表状态。复制链表中的指针都不应指向原链表中的节点 。
- //例如,如果原链表中有 X 和 Y 两个节点,其中 X.random --> Y 。那么在复制链表中对应的两个节点 x 和 y ,同样有 x.random --> y 。
- //返回复制链表的头节点。
- public class Top30 {
- public class Node {
- public int val;
- public Node next;
- public Node random;
-
- public Node() {
- }
-
- public Node(int val, Node next, Node random) {
- this.val = val;
- this.next = next;
- this.random = random;
- }
-
- public Node(int val) {
- this.val = val;
- this.next = null;
- this.random = null;
- }
-
- }
-
- public Node copyRandomList(Node head) {
- if (head == null) {
- return null;
- }
-
- Map
nodeMap = new HashMap<>(); - Node cur = head;
-
- // 构建原链表和新链表的映射
- while (cur!=null){
- nodeMap.put(cur,new Node(cur.val));
- cur = cur.next;
- }
-
- cur = head;
-
- // 构建新链表的映射关系
- while(cur!=null){
- nodeMap.get(cur).next = nodeMap.get(cur.next);
- nodeMap.get(cur).random = nodeMap.get(cur.random);
- cur = cur.next;
- }
-
- return nodeMap.get(head);
- }
- }