C++ simple O(n) time, in-place solution


  • 0
    M
        vector<ListNode*> splitListToParts(ListNode* root, int k) {
            ListNode* r=root;
            int size=0;
            while(r) {
                size++;
                r=r->next;
            }
            int s=size/k, ct=size-s*k;
            vector<ListNode*> res;
            for(int i=0;i<k;i++) {
                int n=1;
                res.push_back(root);
                while(root&&n<s) {
                    root=root->next;
                    n++;
                }
                if(root&&ct>0&&s!=0) root=root->next; 
                if(root) {
                    ListNode* tmp=root;
                    root=root->next;
                    tmp->next=NULL;
                }
                ct--;
            }
            return res;
        }

Log in to reply
 

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