題目:
Given a (singly) linked list with head node
root
, write a function to split the linked list into
k
consecutive linked list "parts".
The length of each part should be as equal as possible: no two parts should have a size differing by more than 1. This may lead to some parts being null.
The parts should be in order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal parts occurring later.
Return a List of ListNode's representing the linked list parts that are formed.
Examples 1->2->3->4, k = 5 // 5 equal parts [ [1], [2], [3], [4], null ]
Example 1:
Input:
root = [1, 2, 3], k = 5
Output: [[1],[2],[3],[],[]]
Explanation:
The input and each element of the output are ListNodes, not arrays.
For example, the input root has root.val = 1, root.next.val = 2, \root.next.next.val = 3, and root.next.next.next = null.
The first element output[0] has output[0].val = 1, output[0].next = null.
The last element output[4] is null, but it's string representation as a ListNode is [].
Example 2:
Input:
root = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], k = 3
Output: [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]]
Explanation:
The input has been split into consecutive parts with size difference at most 1, and earlier parts are a larger size than the later parts.
Note:
- The length of
will be in the rangeroot
.[0, 1000]
- Each value of a node in the input will be an integer in the range
.[0, 999]
-
will be an integer in the rangek
[1, 50]
.
思路:
我們采用遞歸來求解:首先計算對外連結表的長度length,這樣根據length和k的關系,就可以知道第一段連結清單需要多長了。是以我們首先分割出第一段,然後再遞歸地分割後續的連結清單。需要注意的是在某些情況下需要拆分的長度可能大于連結清單的長度,這樣就會導緻最終拆分結果的個數不足k,是以在傳回之前我們還需要用空指針來填充。
代碼:
/** * 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) { int length = 0; ListNode *node = root; while (node != NULL) { ++length; node = node->next; } vector<ListNode*> ret; splitListToParts(root, ret, k, length); while (ret.size() < k) { ret.push_back(NULL); } return ret; } private: void splitListToParts(ListNode *root, vector<ListNode*> &ret, int k, int length) { if (root == NULL) { return; } if (k == 1) { ret.push_back(root); return; } int size = length / k, remain = length % k; if (remain != 0) { ++size; } ListNode *node = root; for (int i = 1; i < size; ++i) { node = node->next; } ListNode *next_root = node->next; node->next = NULL; ret.push_back(root); splitListToParts(next_root, ret, k - 1, length - size); } };