题目描述:
解题思路:
这道题跟普通的复制链表的思路一样,不同的是他有个random指向。首先创建一个新的链表,通过递归调用的方式,不断把值赋给新的链表。同时我们通过一个Map集合来保存random的指向,根据random,我们可以在Map集合中找到之前random指针指向的node节点,并把它赋值给random指针。
代码实现:
class Solution {
Map<Node,Node> nodeMap = new HashMap<>();
public Node copyRandomList(Node head) {
if(head == null){
return null;
}
//复制节点
Node cur = new Node(head.val);
//存入map
nodeMap.put(head, cur);
//递归调用,当前cur.next = 下一层返回的cur
cur.next = copyRandomList(head.next);
//如果当前head节点random不为null,根据map找到对应的新节点
if(head.random != null){
cur.random = nodeMap.get(head.random);
}
return cur;
}
}
执行结果: