diff --git a/cs/split-linked-list-in-parts.cs b/cs/split-linked-list-in-parts.cs new file mode 100644 index 0000000..85b4a90 --- /dev/null +++ b/cs/split-linked-list-in-parts.cs @@ -0,0 +1,39 @@ +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; + } +}