40 lines
975 B
C#
40 lines
975 B
C#
|
public class Solution {
|
||
|
private int GetLength(ListNode node) {
|
||
|
var count = 0;
|
||
|
|
||
|
for (; node != null; node = node.next) {
|
||
|
++count;
|
||
|
}
|
||
|
|
||
|
return count;
|
||
|
}
|
||
|
|
||
|
public ListNode[] SplitListToParts(ListNode tail, int k) {
|
||
|
var parts = new ListNode[k];
|
||
|
Array.Fill(parts, null);
|
||
|
|
||
|
var listLength = GetLength(tail);
|
||
|
var (perPart, leftover) = (listLength / k, listLength % k);
|
||
|
|
||
|
for (var i = 0; i < k && tail != null; ++i) {
|
||
|
var (node, length) = (tail, perPart);
|
||
|
parts[i] = node;
|
||
|
|
||
|
if (leftover > 0) {
|
||
|
++length;
|
||
|
--leftover;
|
||
|
}
|
||
|
|
||
|
// Add the regular part
|
||
|
for (var j = 0; j < length - 1; ++j) {
|
||
|
node = node.next;
|
||
|
}
|
||
|
|
||
|
// Handle the last node in the part as a special case
|
||
|
(tail, node.next) = (node.next, null);
|
||
|
}
|
||
|
|
||
|
return parts;
|
||
|
}
|
||
|
}
|