https://leetcode.com/problems/split-linked-list-in-parts/
1. Split Input list:
//8 ms 8.4 MB/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode() : val(0), next(nullptr) {}* ListNode(int x) : val(x), next(nullptr) {}* ListNode(int x, ListNode *next) : val(x), next(next) {}* };*/class Solution {public:vector<ListNode*> splitListToParts(ListNode* root, int k) {vector<ListNode*> result;int n = 0;ListNode* curr = root;//get the length of the listwhile(curr){curr = curr->next;n++;}int width = n / k; //width of a blockint rest = n % k; //rest of elements//cout << width << " " << rest << endl;curr = root;ListNode* head = curr;ListNode* prev = curr;for(int i = 0; i < k; i++){head = curr;for(int j = 0; j < width - 1 + (i < rest ? 1 : 0); j++){if(curr)curr = curr->next;}if(curr){prev = curr;curr = curr->next;prev->next = NULL;}result.push_back(head);}return result;}};//about "width - 1 + (i < rest ? 1 : 0)"//if k > n, there is no enough space for each block to has at least 1 element//so that for example/*Input:root = [1, 2, 3], k = 5Output: [[1],[2],[3],[],[]]*///width = 1, rest = 3//when i < 3, j = 0, and j++ until j < (1 - 1 + 1), so curr only move 1 step at a time//when i >= 3, j = 0, and j++ until j < (1 - 1 + 0), so curr could not move anymore, and pushes empty lists/*Input:root = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], k = 3Output: [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]]*///width = 3, rest = 1//when i<1, j = 0, and j++ until j < (3 - 1 + 1), so curr moves 3 steps at a time//when i>=1, j = 0, and j++ until j < (3 - 1 + 0), so curr moves 2 steps at a time
- Time Complexity: O(N + k), where N is the number of nodes in the given list. If k is large, it could still require creating many new empty lists.
- Space Complexity: O(k), the additional space used in writing the answer.
