题目描述:
请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。
实例:

思路:
通过创建HashMap,将 head 与新创建的Node相对应即可。
代码:
/*
// 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) {
if(head==null) return null;//如果为空,即返回也是null。
Node new1 = head;//新创建一个Node,作用是不破坏原来的 head。
Map<Node,Node> map = new HashMap<>();//创建Map
while(new1!=null){
map.put(new1,new Node(new1.val));//讲对应的val传入到 HashMap 中。
new1 = new1.next;
}
new1 = head;
while(new1 != null){
map.get(new1).next = map.get(new1.next);//指向传递
map.get(new1).random = map.get(new1.random);//random传递
new1 = new1.next;
}
return map.get(head);
}
}
结果:

这篇博客介绍了一个复杂的链表数据结构,其中每个节点不仅包含一个next指针指向下一个节点,还有一个random指针可以指向链表中的任意节点或null。文章提供了使用HashMap来复制这个复杂链表的解决方案,通过遍历链表并创建新的映射关系,实现了对原链表的完整复制,包括random指针的正确指向。
797

被折叠的 条评论
为什么被折叠?



