思路:根据题目要求,先算出链表长度,然后算每个部分需要多少个节点,(这里需要注意的是,前N%K需要比正常的多出1个,这样就满足有剩余的情况)
代码
class Solution {
public ListNode[] splitListToParts(ListNode root, int k) {
ListNode[] ans = new ListNode[k];
ListNode head =root;
int N = 0;
while(head != null)
{
head = head.next;
N ++;
}
int size = N / k;
int cur = N % k;
for(int i = 0; i < k; i ++)
{
ListNode newNode = new ListNode(0);
ListNode h = newNode;
int num = i < cur ? size + 1: size;
for(int j = 0; j < num; j++)
{
h.next = new ListNode(root.val);
h = h.next;
root = root.next;
}
ans[i] = newNode.next;
}
return ans;
}
}