File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments