#725

Split Linked List in Parts

pupil · 555 · lc medium +28 · verified · 70.5% accepted · 4,717 likes · top 79%

Description

Given the head of a singly linked list and an integer k, divide the list into k consecutive parts that preserve the original order. Part sizes must differ by at most one, and earlier parts are at least as long as later ones. Some parts may be null if the list is shorter than k. Return an array of the k part heads.

Example 1:

Input: head = [1,2,3], k = 5
Output: [[1],[2],[3],[],[]]
Explanation:
The first element output[0] has output[0].val = 1, output[0].next = null.
The last element output[4] is null, but its string representation as a ListNode is [].

Example 2:

Input: head = [1,2,3,4,5,6,7,8,9,10], k = 3
Output: [[1,2,3,4],[5,6,7],[8,9,10]]
Explanation:
The input has been split into consecutive parts with size difference at most 1, and earlier parts are a larger size than the later parts.

Code

1
2
3
4
5
6
7
8