题目描述:给一个长度为 n 的链表,每个节点包含一个额外增加的随机指针 random ,该指针可以指向链表中的任何节点或空节点。
构造这个链表的 深拷贝。 深拷贝应该正好由 n 个 全新 节点组成,其中每个新节点的值都设为其对应的原节点的值。新节点的 next 指针和 random 指针也都应指向复制链表中的新节点,并使原链表和复制链表中的这些指针能够表示相同的链表状态。复制链表中的指针都不应指向原链表中的节点 。
例如,如果原链表中有 X 和 Y 两个节点,其中 X.random --> Y 。那么在复制链表中对应的两个节点 x 和 y ,同样有 x.random --> y 。
返回复制链表的头节点。
链接:https://leetcode-cn.com/problems/copy-list-with-random-pointer
求解思路:
- 创建一个 Map ,key 为旧节点,value 为新节点;
- 遍历旧链表,创建旧节点对应的新节点,并插入到 Map 中;
- 再次遍历旧链表,分别将 next 和 random 连接上;
- 返回 head 对应的 value ,即新链表的头节点。
代码实现:
/*
// 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) {
//创建一个Map,key为旧节点,value为新节点
Map<Node,Node> map = new HashMap<>();
//遍历旧链表,创建新链表的节点
for(Node cur = head;cur != null;cur = cur.next){
map.put(cur,new Node(cur.val));
}
//再遍历旧链表,分别连接next和random
for(Node cur = head;cur != null;cur = cur.next){
//取出cur对应的新节点
Node newNode = map.get(cur);
//取出cur.next对应的新节点
Node newNextNode = map.get(cur.next);
//将next连接上
newNode.next = newNextNode;
//将random连接上
map.get(cur).random = map.get(cur.random);
}
return map.get(head);//返回值为旧链表头节点key对应的value(新链表头节点)
}
}