-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcopyListWithRandomPointer.ts
More file actions
39 lines (33 loc) · 1.14 KB
/
Copy pathcopyListWithRandomPointer.ts
File metadata and controls
39 lines (33 loc) · 1.14 KB
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
// Definition for Node.
class LinkedListNode {
val: number
next: LinkedListNode | null
random: LinkedListNode | null
constructor(val?: number, next?: LinkedListNode, random?: LinkedListNode) {
this.val = (val===undefined ? 0 : val)
this.next = (next===undefined ? null : next)
this.random = (random===undefined ? null : random)
}
}
// Time complexity: O(n) where n is the length of the linked list
// Space complexity: O(n)
function copyRandomList(head: LinkedListNode | null): LinkedListNode | null {
const dummyHead: LinkedListNode = new LinkedListNode()
let curr: LinkedListNode = dummyHead
let currOld: LinkedListNode = head
const map = new Map<LinkedListNode, LinkedListNode>()
while (currOld != null) {
curr.next = new LinkedListNode(currOld.val)
map.set(currOld, curr.next)
curr = curr.next
currOld = currOld.next
}
currOld = head
while (currOld != null) {
if (currOld.random != null) {
map.get(currOld).random = map.get(currOld.random)
}
currOld = currOld.next
}
return dummyHead.next
};