vector<ListNode*> splitListToParts(ListNode* root, int k) {
vector<ListNode*> nd(k, root);
if(root == nullptr) return nd;
ListNode* p = root;
int N=0;
while(p) {
N++;
p = p->next;
}
int n2 = N/k, n1 = n2+1;
int k1 = N - n2*k, k2 = k - k1;
p = root;
for(int i=0; i<k; i++) {
if(i<k1) {
nd[i] = p;
int j=0;
while(j<n1-1) {
p=p->next;
j++;
}
ListNode* q = p;
p = p->next;
q->next = nullptr;
}
else {
nd[i] = p;
if(p==nullptr) continue;
int j=0;
while(j<n2-1) {
p=p->next;
j++;
}
ListNode* q = p;
p = p->next;
q->next = nullptr;
}
}
return nd;
}
No comments:
Post a Comment