leetcodeSolution to some Leetcode problems written in C++ |
git clone git://git.dimitrijedobrota.com/leetcode.git |
Log | Files | Refs | README | LICENSE |
0725.cpp (860B)
0 class Solution {
1 public:
2 vector<ListNode *> splitListToParts(ListNode *head, int k) {
3 int size = 0, part, extra;
5 for (ListNode *tmp = head; tmp; tmp = tmp->next)
6 size++;
7 if (k >= size) {
8 part = 1;
9 extra = 0;
10 } else {
11 part = size / k;
12 extra = size - (part * k);
13 }
15 vector<ListNode *> res;
16 ListNode *crnt = head, *tmp;
17 while (size >= part) {
18 res.push_back(crnt);
19 for (int i = 1; i < part; i++)
20 crnt = crnt->next;
21 if (extra-- > 0) crnt = crnt->next, size--;
22 size -= part;
23 tmp = crnt->next;
24 crnt->next = nullptr;
25 crnt = tmp;
26 }
28 while (res.size() < k)
29 res.push_back(nullptr);
31 return res;
32 }
33 };