1、题目描述
2、题目分析
主要是理解题意,将每个子链表应该分得的节点个数计算清楚。利用除数和余数的方法进行计算。
3、代码
1 vector<ListNode*> splitListToParts(ListNode* root, int k) { 2 vector<ListNode*> res(k, NULL); 3 if (root == NULL) { 4 return res; 5 } 6 7 int listlen = 0; 8 ListNode *p = root; 9 while (p != NULL) { 10 listlen++; 11 p = p->next; 12 } 13 14 int m = listlen / k; 15 int n = listlen % k; 16 17 if (m == 0) { 18 p = root; 19 for (int i = 0; i < n; i++) { 20 res[i] = p; 21 ListNode *pn = p->next; 22 p->next = NULL; 23 p = pn; 24 } 25 } else { 26 p = root; 27 int i; 28 for(i = 0; i < k; i++) { 29 ListNode *pn; 30 res[i] = p; 31 int step = (i < n)? m:m-1; 32 while(step--) { 33 p = p->next; 34 } 35 pn = p->next; 36 p->next = NULL; 37 p = pn; 38 if (p == NULL) 39 break; 40 } 41 } 42 43 44 return res; 45 46 47 48 }