725. 分隔链表
题目链接
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/split-linked-list-in-parts/
题目描述
题目分析
返回的数组中里放着链表。
/**
* 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);// 注意 初始值
int n = 0;
ListNode* temp = head;
while(temp){
n++;
temp = temp->next;
}
int quotient = n / k, remainder = n % k;
ListNode* cur = head;
// 要注意示例1的情况
for(int i = 0; i < k && cur != nullptr; i++){//注意这里是按照分隔后一段一段来遍历的
int size = quotient + (i < remainder ? 1 : 0);
res[i] = cur;
// 分隔
for(int j = 1; j < size; j++){
cur = cur->next;
}
ListNode* next = cur->next;
cur->next = nullptr;
cur = next;
}
return res;
}
};