Advertisement
nikunjsoni

725

Mar 21st, 2021
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.93 KB | None | 0 0
  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.         ListNode *node, *prev;
  15.         int len, n, r;
  16.        
  17.         len = 0;
  18.         node = root;
  19.         while(node){
  20.             len++;
  21.             node = node->next;
  22.         }
  23.        
  24.         n = len/k; r = len%k;
  25.         vector<ListNode*> parts(k, NULL);
  26.         node = root;
  27.        
  28.         for(int i=0; i<k && node; i++,r--){
  29.             parts[i] = node;
  30.             for(int j=0; j<n+(r>0); j++){
  31.                 prev = node;
  32.                 node = node->next;
  33.             }
  34.             prev->next = NULL;
  35.         }
  36.         return parts;
  37.     }
  38. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement