forked from chihungyu1116/leetcode-javascript
-
Notifications
You must be signed in to change notification settings - Fork 14
/
138 Copy List With Random Pointer.js
46 lines (35 loc) · 1.01 KB
/
138 Copy List With Random Pointer.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
// A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
// Return a deep copy of the list.
// Hide Company Tags Amazon Microsoft Bloomberg Uber
// Show Tags
// Show Similar Problems
/**
* 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) {
var hashMap = {};
var newHead = new RandomListNode(0);
newHead.next = copyList(head);
function copyList(node) {
if(node === null) {
return node;
}
if(hashMap[node.label]) {
return hashMap[node.label];
}
var newNode = new RandomListNode(node.label);
hashMap[node.label] = newNode;
newNode.next = copyList(node.next);
newNode.random = copyList(node.random);
return newNode;
}
return newHead.next;
};