Easy to understand clean Java code


  • 0
    B

    My solution.

    public ListNode[] splitListToParts(ListNode root, int k) {
            ListNode[] res = new ListNode[k];
            if (root == null) return res;
    
            ListNode curr = root;
            int len = 0;
            while (curr != null) {
              len++;
              curr = curr.next;
            }
    
            int div = len / k;
            int rem = len % k;
            ListNode dummy = new ListNode(0);
            dummy.next = root;
            for (int i=0; i<k; i++) {
                ListNode prev = dummy;
                for (int j=0; j<div; j++) {
                	prev = prev.next;
                }
                if (rem > 0) {
                	prev = prev.next;
                	rem--;
                }
                res[i] = dummy.next;
                dummy.next = prev.next;
                prev.next = null;
            }
            return res;
    }
    

Log in to reply
 

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