AcWing 48. 复杂链表的复刻-JavaScript
原题链接
中等
作者:
semicloud
,
2024-02-27 14:19:26
,
所有人可见
,
阅读 28
function ListNode(val) {
this.val = val;
this.next = this.random = null;
}
/**
* @param {ListNode} head
* @return {ListNode}
*/
var copyRandomList = function(head) {
if (!head) return head;
const hash = new Map();
let p = head;
while (p) {
// 对每一个节点,创建对应的节点,放入哈细表中
const newNode = new ListNode(p.val);
hash.set(p, newNode);
p = p.next;
}
p = head;
while (p) {
// 新节点的next对应旧节点在哈希表中的next
hash.get(p).next = hash.get(p.next) ? hash.get(p.next) : null;
hash.get(p).random = hash.get(p.random) ? hash.get(p.random) : null;
p = p.next;
}
return hash.get(head);
};