?
链接:725. 分隔链表
题解:力扣
?
/**
* 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(k, nullptr);
if (!head) {
return res;
}
int len = 0;
ListNode* cur = head;
while (cur) {
++len;
cur = cur->next;
}
int cnt = len/k; // 每段几个
int remain = len%k; // 补充的余数
int i = 0;
ListNode* prev = head;
while (head) {
res[i++] = head; // 每一段的开始
for (int i = 0; i < cnt; ++i) {
if (head) {
prev = head;
head = head->next;
}
}
if (remain > 0) {
prev = head;
head = head->next;
--remain;
}
// 结束一段
prev->next = nullptr;
}
// RVO
return res;
}
};
?
|