[725. Split Linked List in Parts] C++ AC


  • 0

    Just remember to cut the the linked list after you push the current list into the final result vector.

    class Solution {
    public:
    vector<ListNode*> splitListToParts(ListNode* root, int k) {
        vector<ListNode*> res;
        int len = 0;
        ListNode* temp = root;
        while(temp){
            len++;
            temp = temp->next;
        }
        if(len <= k){
            while(res.size() < k){
                res.push_back(root);
                if(root){
                    ListNode* r = root->next;
                    root->next = nullptr;
                    root = r;
                }
            }
        }else{
            int more = len % k;
            int base = len/k;
            while(res.size() < k){
                int count = 1;
                ListNode* r = root;
                while(count < base + (more > 0 ? 1 : 0)) {r = r->next; count++;}
                res.push_back(root);
                ListNode* r2 = r->next;
                r->next = nullptr;
                r = r2;
                root = r;
                if(more > 0) more--;
            }
        }
        return res;
    }
    

    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.