-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path138.copy-list-with-random-pointer.ts
61 lines (50 loc) · 1.57 KB
/
138.copy-list-with-random-pointer.ts
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
50
51
52
53
54
55
56
57
58
59
60
61
class MyNode {
val: number;
next: MyNode | null;
random: MyNode | null;
constructor(val?: number, next?: MyNode, random?: MyNode) {
this.val = val === undefined ? 0 : val;
this.next = next === undefined ? null : next;
this.random = random === undefined ? null : random;
}
}
function copyRandomList(head: MyNode | null): MyNode | null {
const map = new Map<MyNode, MyNode>();
const dummy = new MyNode();
let currentOldNode = head;
let currentNewNode = dummy;
while (currentOldNode) {
const newNode = new MyNode(currentOldNode.val);
currentNewNode.next = newNode;
map.set(currentOldNode, newNode);
currentOldNode = currentOldNode.next;
currentNewNode = currentNewNode.next;
}
currentOldNode = head;
while (currentOldNode) {
currentNewNode = map.get(currentOldNode)!;
if (currentOldNode.random !== null) {
currentNewNode.random = map.get(currentOldNode.random)!;
}
currentOldNode = currentOldNode.next;
}
return dummy.next;
}
function copyRandomList2(head: MyNode | null): MyNode | null {
const map = new Map<MyNode | null, MyNode | null>([[null, null]]);
let currentNode: MyNode | null = null;
currentNode = head;
while (currentNode) {
map.set(currentNode, new MyNode());
currentNode = currentNode.next;
}
currentNode = head;
while (currentNode) {
const newNode = map.get(currentNode)!;
newNode.val = currentNode.val;
newNode.next = map.get(currentNode.next)!;
newNode.random = map.get(currentNode.random)!;
currentNode = currentNode.next;
}
return map.get(head)!;
}