浅拷贝: 返回地址一样的链表。
深拷贝: 返回地址不一样,但关系一致的链表。
给你一个长度为 n 的链表,每个节点包含一个额外增加的随机指针 random ,该指针可以指向链表中的任何节点或空节点。
构造这个链表的 深拷贝。 深拷贝应该正好由 n 个 全新 节点组成,其中每个新节点的值都设为其对应的原节点的值。新节点的 next 指针和 random 指针也都应指向复制链表中的新节点,并使原链表和复制链表中的这些指针能够表示相同的链表状态。复制链表中的指针都不应指向原链表中的节点 。
例如,如果原链表中有 X 和 Y 两个节点,其中 X.random --> Y 。那么在复制链表中对应的两个节点 x 和 y ,同样有 x.random --> y 。
返回复制链表的头节点。
解法一:
class Solution {
public Node copyRandomList(Node head) {
if(head == null) return null;
Map<Node,Node> map = new HashMap<>();
Node temp = head;
while(temp != null){
map.put(temp,new Node(temp.val)); //新链表(val== 原链表)和原链表构成键值对
temp = temp.next;
}
temp = head;
while(temp != null){ //第二次遍历,通过键值对将map中的新链表(next,random)串联起来
map.get(temp).next = map.get(temp.next);
map.get(temp).random = map.get(temp.random);
temp = temp.next;
}
return map.get(head);
}
}
解法二:
我们首先将该链表中每一个节点拆分为两个相连的节点,例如对于链表 A→B→CA \rightarrow B \rightarrow CA→B→C,我们可以将其拆分为 A→A′→B→B′→C→C′A \rightarrow A' \rightarrow B \rightarrow B' \rightarrow C \rightarrow C'A→A′→B→B′→C→C′。对于任意一个原节点 SSS,其拷贝节点 S′S'S′ 即为其后继节点。
这样,我们可以直接找到每一个拷贝节点 S′S'S′ 的随机指针应当指向的节点,即为其原节点 SSS 的随机指针指向的节点 TTT 的后继节点 T′T'T′。需要注意原节点的随机指针可能为空,我们需要特别判断这种情况。
当我们完成了拷贝节点的随机指针的赋值,我们只需要将这个链表按照原节点与拷贝节点的种类进行拆分即可,只需要遍历一次。同样需要注意最后一个拷贝节点的后继节点为空,我们需要特别判断这种情况。
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/copy-list-with-random-pointer/solution/fu-zhi-dai-sui-ji-zhi-zhen-de-lian-biao-rblsf/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
class Solution {
public Node copyRandomList(Node head) {
if (head == null) {
return null;
}
for (Node node = head; node != null; node = node.next.next) {
Node nodeNew = new Node(node.val);
nodeNew.next = node.next;
node.next = nodeNew;
}
for (Node node = head; node != null; node = node.next.next) {
Node nodeNew = node.next;
nodeNew.random = (node.random != null) ? node.random.next : null;
}
Node headNew = head.next;
for (Node node = head; node != null; node = node.next) {
Node nodeNew = node.next;
node.next = node.next.next;
nodeNew.next = (nodeNew.next != null) ? nodeNew.next.next : null;
}
return headNew;
}
}
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/copy-list-with-random-pointer/solution/fu-zhi-dai-sui-ji-zhi-zhen-de-lian-biao-rblsf/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。