Split Linked List in Parts
Thoughts
Code
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
private int size(ListNode head) {
int count = 0;
while (head != null) {
count++;
head = head.next;
}
return count;
}
public ListNode[] splitListToParts(ListNode root, int k) {
ListNode[] res = new ListNode[k];
res[0] = root;
ListNode node = root, prior = null;
int size = size(root);
int len = size > k ? size / k : 1;
int residual = size > k ? size % k : 0;
int start = 0;
for (; start < residual; start++) {
res[start] = node;
if (prior != null) {
prior.next = null;
}
for (int j = 0; j <= len && node != null; j++) {
prior = node;
node = node.next;
}
}
for (int i = start; i < k; i++) {
res[i] = node;
if (prior != null) {
prior.next = null;
}
for (int j = 0; j < len && node != null; j++) {
prior = node;
node = node.next;
}
}
return res;
}
}Analysis
Last updated