Partition a Linked List into K continuous groups with difference in their sizes at most 1 | Java program for the above approach ; 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
import java . util . * ; class GFG { static class ListNode { int val ; ListNode next ; } ; static ListNode push ( ListNode head_ref , int node_val ) { ListNode new_node = new ListNode ( ) ; new_node . val = node_val ; new_node . next = head_ref ; head_ref = new_node ; return head_ref ; } static void splitListInParts ( ListNode head , int K ) { Vector < ListNode > ans = new Vector < ListNode > ( ) ; if ( head == null ) { while ( K -- > 0 ) ans . add ( null ) ; } int N = 0 ; ListNode p = head ; while ( p . next != null ) { p = p . next ; N ++ ; } int len = N / K ; int rem = N % K ; p = head ; while ( K > 0 && p . next != null ) { int x = len ; ListNode curr_head = p ; ListNode last = p ; if ( rem > 0 ) { p = p . next ; rem -- ; } while ( x -- > 0 ) { if ( last == p ) p = p . next ; else { last . next = p ; last = p ; p = p . next ; } } last . next = null ; ans . add ( curr_head ) ; K -- ; } while ( K > 0 ) { ans . add ( null ) ; K -- ; } System . out . print ( " { " ) ; for ( int i = 0 ; i < ans . size ( ) ; i ++ ) { System . out . print ( " { " ) ; while ( ans . get ( i ) != null ) { System . out . print ( ans . get ( i ) . val + " ▁ " ) ; ans . set ( i , ans . get ( i ) . next ) ; } System . out . print ( " } " ) ; if ( i != ans . size ( ) - 1 ) System . out . print ( " , ▁ " ) ; } System . out . print ( " } " ) ; } public static void main ( String [ ] args ) { ListNode root = new ListNode ( ) ; root = push ( root , 8 ) ; root = push ( root , 7 ) ; root = push ( root , 6 ) ; root = push ( root , 5 ) ; root = push ( root , 4 ) ; root = push ( root , 3 ) ; root = push ( root , 2 ) ; root = push ( root , 1 ) ; int K = 3 ; splitListInParts ( root , K ) ; } }