Skip to content

Commit ed2c18d

Browse files
t3chkidt3chkid
authored andcommitted
add solution for 138.Copy List With Random Pointer in Kotlin
1 parent 7b13263 commit ed2c18d

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package kotlin
2+
3+
class Node(var `val`: Int) {
4+
var next: Node? = null
5+
var random: Node? = null
6+
}
7+
8+
class Solution {
9+
fun copyRandomList(node: Node?): Node? {
10+
if (node == null) return null
11+
val hashMap = HashMap<Node, Node>()
12+
val dummyNode = Node(-1)
13+
var currentNode = node
14+
var currentResultantListNode: Node? = dummyNode
15+
// create the new linked list ignoring the random pointers
16+
while (currentNode != null) {
17+
val newNode = Node(currentNode.`val`)
18+
currentResultantListNode?.next = newNode
19+
// associate the node of the original list to the related new node
20+
hashMap[currentNode] = newNode
21+
currentResultantListNode = newNode
22+
currentNode = currentNode.next
23+
}
24+
currentNode = node
25+
currentResultantListNode = dummyNode.next
26+
// make the "random" pointers of each node in the new list,
27+
// match those of the original list
28+
while (currentNode != null) {
29+
if (currentNode.random != null) currentResultantListNode?.random = hashMap[currentNode!!.random]
30+
currentNode = currentNode.next
31+
currentResultantListNode = currentResultantListNode?.next
32+
}
33+
return dummyNode.next
34+
}
35+
}

0 commit comments

Comments
 (0)