Leetcode 725. Split Linked List in Parts
You are given the head of a singly linked list and an integer k
. Split the linked list into k
consecutive linked list parts.
The length of each part should be as equal as possible: no two parts should have a size differing by more than one. This may lead to some parts being null if there are not enough nodes to distribute.
The parts should be in the order of occurrence in the input list, and parts occurring earlier should never be smaller than parts occurring later.
Return an array of the k
parts.
k
empty parts.class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public class Solution {
public ListNode[] splitListToParts(ListNode head, int k) {
// Step 1: Find the total length of the linked list.
int totalLength = 0;
ListNode current = head;
while (current != null) {
totalLength++;
current = current.next;
}
// Step 2: Determine the size of each part and the number of larger parts needed.
int partSize = totalLength / k;
int extraNodes = totalLength % k;
ListNode[] result = new ListNode[k];
current = head;
for (int i = 0; i < k; i++) {
ListNode dummy = new ListNode(0);
ListNode write = dummy;
// Determine how many nodes this part should contain
int currentPartSize = partSize + (i < extraNodes ? 1 : 0);
for (int j = 0; j < currentPartSize; j++) {
write = write.next = new ListNode(current.val);
if (current != null) {
current = current.next;
}
}
result[i] = dummy.next;
}
return result;
}
}
totalLength / k
nodes. The first totalLength % k
parts get one additional node each.Do you have any specific questions or requirements about the approach?
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?