Simple and easy to understand Java solution


  • 0
    A

    class Solution {
    public ListNode[] splitListToParts(ListNode root, int k) {
    ListNode[] res = new ListNode[k];
    int len = size(root);
    int q = len/k;
    int r = len%k;

        ListNode cur = root;
        int i=0;
        
        while(cur!=null){
            ListNode head = new ListNode(0);
            ListNode temp = head;
            if(r>0){
                int n = q+1;
                while(n>0){
                    temp.next = cur;
                    temp = temp.next;
                    cur = cur.next;
                    n--;
                }
                r--;
            }else{
                int n = q;
                while(n>0){
                    temp.next = cur;
                    temp = temp.next;
                    cur = cur.next;
                    n--;
                }
            }
            
            temp.next = null;
            res[i++] = head.next;
        }
        
        return res;
        
        
    }
    
    int size(ListNode root){
        ListNode cur = root;
        int count = 0;
        
        while(cur!=null){
            count++;
            cur = cur.next;
        }
        
        return count;
    }
    

    }


Log in to reply
 

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