-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
44 lines (38 loc) · 932 Bytes
/
index.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
/**
* 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) {
if(!head) return head;
var node = head;
while(node){
let tmp = node.next;
node.next = new RandomListNode(node.label);
node.next.next = tmp;
node = tmp;
}
let old = head;
let ans = head.next;
let newN = head.next;
while(old){
newN.random = old.random && old.random.next;
old = old.next.next;
newN = newN.next && newN.next.next;
}
old = head;
newN = head.next;
while(old){
old.next = old.next.next;
old = old.next;
newN.next = old && old.next;
newN = newN.next;
}
return ans;
};