Partition a Linked List into K continuous groups with difference in their sizes at most 1 | Link List Node ; Function to insert a node into the Linked List ; Allocate a new dynamic node ; Update new_node . val ; Stores the head_ref ; Update ( * head_ref ) ; Function to split the linked list in K groups ; Stores the K groups ; If head is null ; Iterate until K is non - zero ; Stores the length of the linked list ; Stores the head node of the linked list ; Iterate over the linked list ; Update p ; Update N ; Iterate over the linked list ; Stores the length of the current group ; Stores the current node ; Stores the previous node ; If rem is greater than 0 ; Update p ; Decrement rem by 1 ; Iterate until x is non - zero ; If the last is equal to p ; Otherwise ; Join the link between last and the current element ; Update the last node ; Update p node ; Assign null to last . next ; Push the current linked list in ans ; Decrement K ; While K greater than 0 ; Update the value of ans ; Increment K ; Print the result ; Print the value ; Update ans [ i ] ; Driver Code
class ListNode { constructor ( ) { this . val = 0 ; this . next = null ; } } ; function pushIn ( head_ref , node_val ) { var new_node = new ListNode ( ) ; new_node . val = node_val ; new_node . next = ( head_ref ) ; head_ref = new_node ; return head_ref ; } function splitListInParts ( head , K ) { var ans = [ ] ; if ( ! head ) { while ( K -- ) ans . push ( null ) ; } var N = 0 ; var p = head ; while ( p ) { p = p . next ; N ++ ; } var len = parseInt ( N / K ) ; var rem = N % K ; p = head ; while ( K > 0 && p ) { var x = len ; var curr_head = p ; var last = p ; if ( rem > 0 ) { p = p . next ; rem -- ; } while ( x -- ) { if ( last == p ) p = p . next ; else { last . next = p ; last = p ; p = p . next ; } } last . next = null ; ans . push ( curr_head ) ; K -- ; } while ( K > 0 ) { ans . push ( null ) ; K -- ; } document . write ( " " ) ; for ( var i = 0 ; i < ans . length ; i ++ ) { document . write ( " " ) ; while ( ans [ i ] ) { document . write ( ans [ i ] . val + " " ) ; ans [ i ] = ans [ i ] . next ; } document . write ( " " ) ; if ( i != ans . length - 1 ) document . write ( " " ) ; } document . write ( " " ) ; } var root = null ; root = pushIn ( root , 8 ) ; root = pushIn ( root , 7 ) ; root = pushIn ( root , 6 ) ; root = pushIn ( root , 5 ) ; root = pushIn ( root , 4 ) ; root = pushIn ( root , 3 ) ; root = pushIn ( root , 2 ) ; root = pushIn ( root , 1 ) ; var K = 3 ; splitListInParts ( root , K ) ;