[LeetCode] Split Linked List in Parts

725. Split Linked List in Parts

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.

The parts should be in the order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal to parts occurring later.

Return an array of the k parts.

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
35
36
37
38
39
40
41
42
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
int sizeOf(ListNode* head) {
int res = 0;
ListNode* runner = head;
while(runner) {
runner = runner->next;
res++;
}
return res;
}
public:
vector<ListNode*> splitListToParts(ListNode* head, int k) {
int n = sizeOf(head), idx = 0;
int req = n / k, padding = n - k * req;
vector<ListNode*> res(k);
ListNode* runner = head;
for(int i = 0; i < k and runner; i++) {
res[i] = runner;
ListNode* last = runner;
for(int j = 0; j < req; j++) {
last = runner;
runner = runner->next;
}
if(padding > i) {
last = runner;
runner = runner->next;
}
if(last) last->next = nullptr;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/10/PS/LeetCode/split-linked-list-in-parts/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.