c# split linked list with minimal node unhooks
42
 public ListNode[] SplitListToParts(ListNode head, int k) {
        ListNode[] result = new ListNode[k];
        
        if ( head == null )
            return result;
        
        //first work out how many nodes there are total.
        int totalNodes = 1;
        var current = head.next;
        while ( current != null )
        {
            totalNodes++;
            current = current.next;
        }
        
        //now we know the size of each list, so we want to go through them all again
        //but this time we'll unhook the nodes and add to result when they are of correct size
        int extras = totalNodes % k;
        int sizeOfLists = totalNodes / k  + ( extras-- > 0 ? 1 : 0);;
        
        int curListIndex = 0;
        int curElementIndex = 1;
        
        current = head;
        result[curListIndex++] = current;
        while ( current != null )
        {
            // If the current node is finished, unhook and start a new one
            // unless current.next is null, in which case we don't need to unhook
            if ( curElementIndex == sizeOfLists && current.next != null )
            {
                //unhook it here, this list is over.
                var temp = current.next;
                current.next = null;
                
                //hook up the next one.
                current = temp;
                result[curListIndex++] = current;
                curElementIndex = 1;
                if ( extras-- == 0 )
                {
                    sizeOfLists--;
                }
            }
            else
            {
                curElementIndex++;
                current = current.next;           
            }
        }
        
        return result;
    }
}
Comments (0)