725. Split Linked List in Parts
https://leetcode.com/problems/split-linked-list-in-parts/
js
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} root
* @param {number} k
* @return {ListNode[]}
*/
var splitListToParts = function(root, k) {
let size = 0
let current = root
while (current) {
size += 1
current = current.next
}
let count = size > k ? (size / k) >> 0 : 1
let extra = size > k ? size % k : 0
current = root
let results = []
while (k > 0) {
let length = count
if (extra) {
length += 1
extra -= 1
}
let start = null
let end = null
for (let i = length; i > 0; i--) {
if (!current) {
break
}
if (!start) {
start = end = current
} else {
end.next = current
end = end.next
}
current = current.next
}
if (end) {
end.next = null
}
results.push(start)
start = null
k -= 1
}
return results
};