1. The title site
https://leetcode.com/problems/split-linked-list-in-parts/
2. Title Description
3. subject to the effect
Given a list and a number k, to be separated from the original list, into continuous k parts.
4. Problem-solving ideas
- First, to get the list of the original length, and calculating how much each part of the element to be stored, the current element and evenly divided into k parts Can, if not, then to put the extra elements in the remaining variables used in the subsequent next traversal
- Traverse the list, each section by counting to see if the number of stored data hit, if hit, will cut off the current list.
5. AC Code
class Solution {
public ListNode[] splitListToParts(ListNode root, int k) {
ListNode temp = root;
int length = 0;
while(temp != null) {
temp = temp.next;
length ++;
}
int each = length / k; // 每一部分要存储多少数据
int remaining = length % k;
ListNode[] ret = new ListNode[k];
temp = root;
for(int i = 0; i < k && temp != null;i++) {
ret[i] = temp;
int total = each - 1 + (remaining -- > 0 ? 1 : 0);
ListNode prev = temp;
while (total -- >= 0 && temp != null) {
prev = temp;
temp = temp.next;
}
prev.next = null; // 截断了
}
return ret;
}
}
6. similar topic
[1] 61. Rotate List title site: https://leetcode.com/problems/rotate-list/
[2] 328. Odd Even Linked List title site: https://leetcode.com/problems/odd-even- linked-list /