725. Split Linked List in Parts
题目意思很简单,给你一串链表,将其分成k个链表。前面链表的长度要大于后面链表的长度。比如说长度为10分成3部分就是[4,3,3]
Example:
Input:
root = [1, 2, 3], k = 5
Output: [[1],[2],[3],[],[]]
Note:
The length of root will be in the range [0, 1000].
Each value of a node in the input will be an integer in the range [0, 999].
k will be an integer in the range [1, 50].
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: vector<ListNode*> splitListToParts(ListNode* root, int k) { vector<ListNode*> res; ListNode* tmp = root; int cnt = 0; while(tmp!=NULL){ cnt++; tmp = tmp->next; } int per_cnt[55] = {0}; for(int i = 0; i < k; i++){ per_cnt[i] = cnt/k; } for(int i=0; i < cnt % k; i++){ per_cnt[i] += 1; } tmp = root; for(int i = 0; i < k; i++){ ListNode* lastPtr = NULL; ListNode* p = NULL; for(int j=0;j<per_cnt[i];j++){ if(tmp == NULL) break; if(j == 0){ lastPtr = new ListNode(tmp->val); p = lastPtr; tmp = tmp -> next; continue; } ListNode* tmpNode = new ListNode(tmp->val); lastPtr -> next = tmpNode; lastPtr = tmpNode; tmp = tmp -> next; } res.push_back(p); } return res; } };
|