forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathsplit-linked-list-in-parts.cpp
41 lines (39 loc) · 982 Bytes
/
split-linked-list-in-parts.cpp
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
// Time: O(n + k)
// Space: O(1)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<ListNode*> splitListToParts(ListNode* root, int k) {
auto n = 0;
auto curr = root;
while (curr) {
curr = curr->next;
n += 1;
}
auto width = n / k;
auto remainder = n % k;
vector<ListNode *> result;
curr = root;
for (int i = 0; i < k; ++i) {
auto head = curr;
for (int j = 0; curr &&
j < width - 1 + static_cast<int>(i < remainder); ++j) {
curr = curr->next;
}
if (curr) {
auto tail = curr;
curr = curr->next;
tail->next = nullptr;
}
result.emplace_back(head);
}
return result;
}
};