-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSplit Linked List in Parts.kt
54 lines (45 loc) · 1.27 KB
/
Split Linked List in Parts.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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
* Example:
* var li = ListNode(5)
* var v = li.`val`
* Definition for singly-linked list.
* class ListNode(var `val`: Int) {
* var next: ListNode? = null
* }
*/
class Solution {
fun splitListToParts(head: ListNode?, k: Int): Array<ListNode?> {
val nodes: MutableList<ListNode?> = mutableListOf()
var curr = head
while (curr != null) {
nodes.add(curr)
curr = curr?.next
}
val nodeArray: Array<ListNode?> = Array(k) { null }
if (nodes.size <= k) {
nodes.forEachIndexed { index, value ->
value?.next = null
nodeArray[index] = value
}
return nodeArray
}
val remaining = nodes.size % k
val count = nodes.size / k
val nodeSize: IntArray = IntArray(k) { 0 }
for (i in 0..k-1) {
nodeSize[i] = count
}
for (i in 0..remaining-1) {
nodeSize[i]++
}
var index = 0
for (i in 0..k-1) {
val count = nodeSize[i]
val lastIndex = index + count - 1
nodes.get(lastIndex)?.next = null
nodeArray[i] = nodes.get(index)
index = lastIndex + 1
}
return nodeArray
}
}