请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。
实例一:
输入:head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
输出:[[7,null],[13,0],[11,4],[10,2],[1,0]]
实例二:
输入:head = [[1,1],[2,1]] 输出:[[1,1],[2,1]]
利用hashMap
/*
// 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<Node , Node> mapNode = new HashMap<>();
mapNode.put(null , null);
Node tmpHead = head;
while(tmpHead != null){
mapNode.put(tmpHead , new Node(tmpHead.val));
tmpHead = tmpHead.next;
}
tmpHead = head;
Node mirrorPre = mapNode.get(tmpHead);
while (tmpHead != null) {
Node mirrorNext = mapNode.get(tmpHead.next);
Node mirrorRandom = mapNode.get(tmpHead.random);
mirrorPre.next = mirrorNext;
mirrorPre.random = mirrorRandom;
mirrorPre = mirrorNext;
tmpHead = tmpHead.next;
}
return mapNode.get(head);
}
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/fu-za-lian-biao-de-fu-zhi-lcof