Java solution, remainder


  • 0
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode[] splitListToParts(ListNode root, int k) {
            int len = 0;
            ListNode p = root, q = root;
            while (p != null) {
                len++; p = p.next;
            }
    
            int each = len / k;
            if (each == 0) each = 1;
            int remainder = len - each * k;
            ListNode[] res = new ListNode[k];
            p = root;
    
            for (int i = 0; i < k; i++) {
                res[i] = p;
                int step = 0;
                if (remainder > 0) {
                    q = q.next;
                    remainder--;
                }
                while (q != null && step < each - 1) {
                    q = q.next; step++;
                }
                if (q != null) {
                    p = q.next;
                    q.next = null;
                }
                q = p;
            }
    
            return res;
        }
    }
    

Log in to reply
 

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