1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-09 15:59:06 +01:00

cs: add «725. Split Linked List in Parts»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-09-08 22:29:00 +02:00
parent 2ee32d75a6
commit 87c2fb3895
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -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;
}
}