-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0138-copy-list-with-random-pointer.kt
35 lines (33 loc) · 1.26 KB
/
0138-copy-list-with-random-pointer.kt
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
package kotlin
class Node(var `val`: Int) {
var next: Node? = null
var random: Node? = null
}
class Solution {
fun copyRandomList(node: Node?): Node? {
if (node == null) return null
val hashMap = HashMap<Node, Node>()
val dummyNode = Node(-1)
var currentNode = node
var currentResultantListNode: Node? = dummyNode
// create the new linked list ignoring the random pointers
while (currentNode != null) {
val newNode = Node(currentNode.`val`)
currentResultantListNode?.next = newNode
// associate the node of the original list to the related new node
hashMap[currentNode] = newNode
currentResultantListNode = newNode
currentNode = currentNode.next
}
currentNode = node
currentResultantListNode = dummyNode.next
// make the "random" pointers of each node in the new list,
// match those of the original list
while (currentNode != null) {
if (currentNode.random != null) currentResultantListNode?.random = hashMap[currentNode!!.random]
currentNode = currentNode.next
currentResultantListNode = currentResultantListNode?.next
}
return dummyNode.next
}
}