Java clear solution with explanation


  • 0
        public ListNode[] splitListToParts(ListNode root, int k) {
            ListNode[] res = new ListNode[k];
            if (k == 0 || root == null) return res;
            int cnt = 0;
            ListNode runner = root;
            while (runner != null) {
                runner = runner.next;
                cnt++;
            }
            // Calculate residue where extra 1 element need to be added to list
            int r = cnt % k;
            // Calculate baseline for each list
            int n = cnt / k;
            runner = root;
            for (int i = 0; i < k; i++) {
                res[i] = runner;
                // Check if it's the first r list
                int loop = (i < r ? 1 : 0) + n;
                for (int j = 0; j < loop; j++) {
                    // If it's the tail of list, set next element to null
                    if (j == loop - 1) {
                        ListNode next = runner.next;
                        runner.next = null;
                        runner = next;
                    } else {
                        runner = runner.next;
                    }
                }
            }
            return res;
        }
    

Log in to reply
 

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