-
Notifications
You must be signed in to change notification settings - Fork 0
/
剑指offer35.fu-za-lian-biao-de-fu-zhi-lcof.js
49 lines (47 loc) · 1.34 KB
/
剑指offer35.fu-za-lian-biao-de-fu-zhi-lcof.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
* // Definition for a Node.
* function Node(val, next, random) {
* this.val = val;
* this.next = next;
* this.random = random;
* };
*/
/**
* @param {Node} head
* @return {Node}
*/
// 递归深拷贝
var copyRandomList = function (head, cachedNode = new WeakMap()) {
if (head === null) {
return null;
}
if (!cachedNode.has(head)) {
cachedNode.set(head, { val: head.val }),
Object.assign(cachedNode.get(head), {
next: copyRandomList(head.next, cachedNode),
random: copyRandomList(head.random, cachedNode),
});
}
return cachedNode.get(head);
};
// 迭代拷贝拆分
var copyRandomList = function (head) {
if (head === null) {
return null;
}
for (let node = head; node !== null; node = node.next.next) {
const newNode = new Node(node.val, node.next, null);
node.next = newNode;
}
for (let node = head; node !== null; node = node.next.next) {
const newNode = node.next;
newNode.random = node.random !== null ? node.random.next : null;
}
const newHead = head.next;
for (let node = head; node !== null; node = node.next) {
const newNode = node.next;
node.next = node.next.next;
newNode.next = node.next !== null ? node.next.next : null;
}
return newHead;
};