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:
parent
2ee32d75a6
commit
87c2fb3895
1 changed files with 39 additions and 0 deletions
39
cs/split-linked-list-in-parts.cs
Normal file
39
cs/split-linked-list-in-parts.cs
Normal 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;
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue