-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path138.js
More file actions
46 lines (41 loc) · 808 Bytes
/
138.js
File metadata and controls
46 lines (41 loc) · 808 Bytes
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
/**
* Definition for singly-linked list with a random pointer.
* function RandomListNode(label) {
* this.label = label;
* this.next = this.random = null;
* }
*/
/**
* @param {RandomListNode} head
* @return {RandomListNode}
*/
var copyRandomList = function(head) {
let temp = head;
let i = 0;
while(temp) {
temp.index = i;
i += 1;
temp = temp.next;
}
list = [];
temp = head;
while(temp) {
list.push(new RandomListNode(temp.label));
temp = temp.next;
}
i = 0;
while(i < list.length - 1) {
list[i].next = list[i + 1];
i += 1;
}
temp = head;
i = 0;
while(temp) {
if (temp.random !== null) {
list[i].random = list[temp.random.index];
}
temp = temp.next;
i += 1;
}
return list.length === 0 ? null : list[0];
};