Leetcode725. 分隔链表
计算出每一段链表长度,分隔链表,分隔的时候,记得存下一个链表头指针防止丢失
/**
* 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 {
public:
vector<ListNode*> splitListToParts(ListNode* head, int k) {
vector<ListNode*> res;
int cnt = 0;
auto p = head, next = p;
while (p) p = p->next, cnt ++ ;
int a = cnt / k, b = cnt % k;
p = head;
while (p) {
res.push_back(p);
for (int i = 0; i < a - 1 + (b != 0); i ++ ) p = p->next;
if (b) {
b -- ;
}
next = p->next;
p->next = nullptr;
p = next;
k --;
}
while (k -- ) res.push_back(nullptr);
return res;
}
};