问题描述
请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。
示例1:
输入:head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
输出:[[7,null],[13,0],[11,4],[10,2],[1,0]]
问题解决
由于在复制链表过程中,需要找到random指针的指向,因此可考虑使用HashMap做缓存。
class Solution {
public Node copyRandomList(Node head) {
if(head == null) return head;
//由于在遍历过程中需要记录random的指针指向,而链表不存在索引,可以使用hashmap做缓存。
Map<Node, Node> map = new HashMap<>();
Node cur = head;
//建立每一个节点的缓存
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);
}
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/fu-za-lian-biao-de-fu-zhi-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。