-
Notifications
You must be signed in to change notification settings - Fork 0
/
Q725_SplitLinkedList_in_parts.cs
69 lines (61 loc) · 1.52 KB
/
Q725_SplitLinkedList_in_parts.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }
*/
public class Solution
{
public ListNode[] SplitListToParts(ListNode head, int k)
{
ListNode[] res = new ListNode[k];
int sizeEachPart = 1;
int size = CountNodes(head);
int redundancies = 0;
if (size > k)
{
sizeEachPart = size / k;
redundancies = size % k;
}
for (int i = 0; i < k; i++)
{
ListNode addItem = head;
int count = 1;
while (count < sizeEachPart && head != null)
{
head = head.next;
count++;
}
if (redundancies > 0 && head != null)
{
head = head.next;
redundancies--;
}
ListNode next = null;
if (head != null)
{
next = head.next;
head.next = null;
}
res[i] = addItem;
head = next;
}
return res;
}
private int CountNodes(ListNode head)
{
ListNode root = head;
int count = 0;
while (root != null)
{
count++;
root = root.next;
}
return count;
}
}