forked from walkccc/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0725.cpp
More file actions
33 lines (29 loc) · 767 Bytes
/
0725.cpp
File metadata and controls
33 lines (29 loc) · 767 Bytes
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
/**
* 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) {
vector<ListNode*> ans(k, NULL);
int len = 0;
for (auto curr = root; curr; curr = curr->next) len++;
int l = len / k;
int r = len % k;
ListNode* head = root;
ListNode* prev = NULL;
for (int i = 0; i < k; i++, r--) {
ans[i] = head;
for (int j = 0; j < l + (r > 0); j++) {
prev = head;
head = head->next;
}
if (prev) prev->next = NULL;
}
return ans;
}
};