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
|
class Solution { public ListNode[] splitListToParts(ListNode head, int k) { ListNode p = head; int n = 0; while (p != null) { p = p.next; ++n; } ListNode[] ans = new ListNode[k]; int groupSize = n / k, reminder = n % k; ListNode cur = head; for (int i = 0; i < k && cur != null; ++i) { ans[i] = cur; int partSize = groupSize + (i < reminder ? 1 : 0); for (int j = 1; j < partSize; ++j) { cur = cur.next; } ListNode next = cur.next; cur.next = null; cur = next; } return ans; } }
|