LeetCode 725. Split Linked List in Parts
原题链接
中等
作者:
haaai
,
2021-02-16 16:28:27
,
所有人可见
,
阅读 525
class Solution {
public:
int count(ListNode* node){
int len = 0;
while (node)
len++, node = node->next;
return len;
}
vector<ListNode*> splitListToParts(ListNode* root, int k) {
vector<ListNode*> head(k, nullptr), tail(k, nullptr);
if (!root) return head;
int len = count(root);
auto p = root;
for (int i = 0; i<k; i++)
for (int j = 0; j < len / k + (i < len % k); j++){
if (head[i] != nullptr)
tail[i]->next = p, tail[i] = p;
else
head[i] = p, tail[i] = p;
p = p->next;
}
for (int i = 0; i<k; i++)
if (tail[i]) tail[i]->next = nullptr;
return head;
}
};