|
| 1 | +/** |
| 2 | + * Definition for singly-linked list. |
| 3 | + * struct ListNode { |
| 4 | + * int val; |
| 5 | + * ListNode *next; |
| 6 | + * ListNode() : val(0), next(nullptr) {} |
| 7 | + * ListNode(int x) : val(x), next(nullptr) {} |
| 8 | + * ListNode(int x, ListNode *next) : val(x), next(next) {} |
| 9 | + * }; |
| 10 | + */ |
| 11 | +class Solution { |
| 12 | +public: |
| 13 | + vector<ListNode*> splitListToParts(ListNode* root, int k) { |
| 14 | + // Create a vector of ListNode pointers to store the k parts. |
| 15 | + vector<ListNode*> parts(k, nullptr); |
| 16 | + |
| 17 | + // Calculate the length of the linked list. |
| 18 | + int len = 0; |
| 19 | + for (ListNode* node = root; node; node = node->next) |
| 20 | + len++; |
| 21 | + |
| 22 | + // Calculate the minimum guaranteed part size (n) and the number of extra nodes (r). |
| 23 | + int n = len / k, r = len % k; |
| 24 | + |
| 25 | + // Initialize pointers to traverse the linked list. |
| 26 | + ListNode* node = root, *prev = nullptr; |
| 27 | + |
| 28 | + // Loop through each part. |
| 29 | + for (int i = 0; node && i < k; i++, r--) { |
| 30 | + // Store the current node as the start of the current part. |
| 31 | + parts[i] = node; |
| 32 | + // Traverse n + 1 nodes if there are remaining extra nodes (r > 0). |
| 33 | + // Otherwise, traverse only n nodes. |
| 34 | + for (int j = 0; j < n + (r > 0); j++) { |
| 35 | + prev = node; |
| 36 | + node = node->next; |
| 37 | + } |
| 38 | + // Disconnect the current part from the rest of the list by setting prev->next to nullptr. |
| 39 | + prev->next = nullptr; |
| 40 | + } |
| 41 | + |
| 42 | + // Return the array of k parts. |
| 43 | + return parts; |
| 44 | + } |
| 45 | +}; |
0 commit comments