leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0725.cpp (860B)


      1 class Solution {
      2   public:
      3     vector<ListNode *> splitListToParts(ListNode *head, int k) {
      4         int size = 0, part, extra;
      5 
      6         for (ListNode *tmp = head; tmp; tmp = tmp->next)
      7             size++;
      8         if (k >= size) {
      9             part = 1;
     10             extra = 0;
     11         } else {
     12             part = size / k;
     13             extra = size - (part * k);
     14         }
     15 
     16         vector<ListNode *> res;
     17         ListNode *crnt = head, *tmp;
     18         while (size >= part) {
     19             res.push_back(crnt);
     20             for (int i = 1; i < part; i++)
     21                 crnt = crnt->next;
     22             if (extra-- > 0) crnt = crnt->next, size--;
     23             size -= part;
     24             tmp = crnt->next;
     25             crnt->next = nullptr;
     26             crnt = tmp;
     27         }
     28 
     29         while (res.size() < k)
     30             res.push_back(nullptr);
     31 
     32         return res;
     33     }
     34 };