-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy path0138_CopyListWithRandomPointer.js
45 lines (43 loc) · 1.08 KB
/
0138_CopyListWithRandomPointer.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
/**
* // 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) {
let clone_map = new Map();
if(head == null){
return null
}
let curr = head;
//copying each element to map.
// in map we have Key (original value) : Value (copy of original value)
while(curr!=null){
clone_map.set(curr, new Node(curr.val));
curr = curr.next
}
curr = head;
while(curr != null){
let next = clone_map.get(curr.next);
if(next){
clone_map.get(curr).next = clone_map.get(curr.next);
} else {
clone_map.get(curr).next = null;
}
let random = clone_map.get(curr.random);
if(random){
clone_map.get(curr).random = random;
} else{
clone_map.get(curr).random = null;
}
curr = curr.next;
}
//console.log(clone_map.get(head))
return clone_map.get(head)
};