解题思路
采用map的方式进行复制。使用深度遍历的方式,我们首先需要拿出所有的节点放入map中,此时map只有当前节点的val值,所以我们还需要找到random 与 next,从而,二次遍历node,从map中去寻找当前节点的next指针与当前节点的rendom指针,最后返回map中我们复制好的节点
const copyRandomList = function(head) {
// 判断边界情况
if (!head) return head
// 复制一个head
let node = head
// 定义map
let map = new Map()
// 遍历, 拿出链表的每一个节点存入map中
while (node) {
map.set(node, new Node(node.val));
node = node.next;
}
node = head
//对map里的新节点进行遍历操作
while (node) {
// 找出map中已经存好的next,拿出来判断是不是有下面的节点
map.get(node).next = map.get(node.next) === undefined ? null :
map.get(node.next)
// map中拿出随机数
map.get(node).random = map.get(node.random)
node = node.next
}
return map.get(head)
};