请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,
每个节点除了有一个 next 指针指向下一个节点,
还有一个 random 指针指向链表中的任意节点或者 null。
分析:1.节点值value的复制:只需要new Node(value,,)就可以
2.节点指针(next,random)的复制(关键)
HashMap<师傅,徒弟> 存储师傅徒弟的关系
第一次遍历把每个值放入哈希map里
再次遍历师傅,把恩仇录传给徒弟
/*
// 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) {
Node cur=head;
HashMap<Node,Node> map=new HashMap<>();
//第一次遍历把每个val放入哈希map里
while(cur!=null){
map.put(cur,new Node(cur.val));
cur=cur.next;
}
//再次遍历师傅,把恩仇录传给徒弟(处理徒弟的指向关系)
cur=head;
while(cur!=null){
map.get(cur).next=map.get(cur.next);
map.get(cur).random=map.get(cur.random);
cur=cur.next;
}
//返回从获取的师傅的头节点
return map.get(head);
}
}
本文介绍如何实现copyRandomList函数,处理复杂链表中带有random指针的节点,通过两次遍历和HashMap存储节点映射,确保复制链表时next和random指针的正确关联。
1044

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



