This is a fairly easy problem
The main idea is to first find the length of the linked list, and then it is easy to find the length of sub linked list.
Figuring out all the cases can be somewhat challenging. Extreme meticulousness is paramount here.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode[] splitListToParts(ListNode root, int k) {
int len = 0;
ListNode count = root;
while(count != null){
len++;
count = count.next;
}
int size = len/k;
int mo = len % k;
ListNode[] result = new ListNode[k];
ListNode temp = root;
for(int i = 0; i < k; i++){
ListNode answer = temp;
int j = size;
if(size == 0){
result[i] = answer;
if(temp != null){
temp = temp.next;
answer.next = null;
continue;
}else{
continue;
}
}
while(j > 1 && temp!=null){
temp = temp.next;
j--;
}
if(mo > 0 && temp!=null){
temp = temp.next;
mo--;
}
ListNode end = temp;
if(temp != null){
temp = temp.next;
end.next = null;
}
result[i] = answer;
}
return result;
}
}