原题:#725_分隔链表
- 将N个节点划分成K份,平均长度为N/K,余数为R=N%K
- 若有K段,就循环K次,每一次产生一段,长度为N/K,每段添加一份R
public ListNode[] splitListToParts(ListNode root, int k) {
ListNode[] ans = new ListNode[k];
int len = 0;
for (ListNode head = root; head != null; head = head.next) ++len;
int l = len / k;
int r = len % k;
ListNode head = root;
ListNode prev = null;
for (int i = 0; i < k; ++i,--r) {
ans[i] = head;
int part_len = l + ((r > 0) ? 1 : 0);
for (int j = 0; j < part_len; ++j) {
prev = head;
head = head.next;
}
if (prev != null) prev.next = null;
}
return ans;
}