share java solution!


  • 0
    T
    /**
     * 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) {
             ListNode cur = root;
             int size = 0;
             while(cur!=null){
                 size++;
                 cur = cur.next;
             }
            
            int count = size/k;;
            int r = size%k;
            
            ListNode[] lists = new ListNode[k];
            ListNode dummy = new ListNode(0);
            cur = dummy;
            dummy.next = root;
            for(int i=0;i<k;i++){
                if(cur.next==null){
                    break;
                }
                int p = count;
                ListNode temp = cur;
                while(p--!=0){
                    cur=cur.next;
                }
                if(r>0){
                    cur=cur.next;
                    r--;
                }
                ListNode next = cur.next;
                cur.next = null;
                lists[i] = temp.next;
                
                dummy.next = next;
                cur = dummy;
            }
            
            return lists;
        }
    }
    

Log in to reply
 

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