https://leetcode.com/problems/split-linked-list-in-parts/

1. Split Input list:

  1. //8 ms 8.4 MB
  2. /**
  3. * Definition for singly-linked list.
  4. * struct ListNode {
  5. * int val;
  6. * ListNode *next;
  7. * ListNode() : val(0), next(nullptr) {}
  8. * ListNode(int x) : val(x), next(nullptr) {}
  9. * ListNode(int x, ListNode *next) : val(x), next(next) {}
  10. * };
  11. */
  12. class Solution {
  13. public:
  14. vector<ListNode*> splitListToParts(ListNode* root, int k) {
  15. vector<ListNode*> result;
  16. int n = 0;
  17. ListNode* curr = root;
  18. //get the length of the list
  19. while(curr){
  20. curr = curr->next;
  21. n++;
  22. }
  23. int width = n / k; //width of a block
  24. int rest = n % k; //rest of elements
  25. //cout << width << " " << rest << endl;
  26. curr = root;
  27. ListNode* head = curr;
  28. ListNode* prev = curr;
  29. for(int i = 0; i < k; i++){
  30. head = curr;
  31. for(int j = 0; j < width - 1 + (i < rest ? 1 : 0); j++){
  32. if(curr)
  33. curr = curr->next;
  34. }
  35. if(curr){
  36. prev = curr;
  37. curr = curr->next;
  38. prev->next = NULL;
  39. }
  40. result.push_back(head);
  41. }
  42. return result;
  43. }
  44. };
  45. //about "width - 1 + (i < rest ? 1 : 0)"
  46. //if k > n, there is no enough space for each block to has at least 1 element
  47. //so that for example
  48. /*
  49. Input:
  50. root = [1, 2, 3], k = 5
  51. Output: [[1],[2],[3],[],[]]
  52. */
  53. //width = 1, rest = 3
  54. //when i < 3, j = 0, and j++ until j < (1 - 1 + 1), so curr only move 1 step at a time
  55. //when i >= 3, j = 0, and j++ until j < (1 - 1 + 0), so curr could not move anymore, and pushes empty lists
  56. /*
  57. Input:
  58. root = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], k = 3
  59. Output: [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]]
  60. */
  61. //width = 3, rest = 1
  62. //when i<1, j = 0, and j++ until j < (3 - 1 + 1), so curr moves 3 steps at a time
  63. //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.