Splitting starting N nodes into new Circular Linked List while preserving the old nodes | Javascript implementation of the approach ; Function to add a node to the empty list ; If not empty ; Creating a node dynamically ; Assigning the data ; Creating the link ; Function to add a node to the beginning of the list ; If list is empty ; Create node ; Assign data ; Function to traverse and print the list ; If list is empty ; Pointing to the first Node of the list ; Traversing the list ; Function to find the length of the CircularLinkedList ; Stores the length ; List is empty ; Iterator Node to traverse the List ; Return the length of the list ; Function to split the first k nodes into a new CircularLinkedList and the remaining nodes stay in the original CircularLinkedList ; Empty Node for reference ; Check if the list is empty If yes , then return null ; NewLast will contain the last node of the new split list itr to iterate the node till the required node ; Update NewLast to the required node and link the last to the start of rest of the list ; Return the last node of the required list ; Driver code ; Append the new last node into the new list ; Print the new lists
class Node { constructor ( ) { let data ; let next ; } } function addToEmpty ( last , data ) { if ( last != null ) return last ; let temp = new Node ( ) ; temp . data = data ; last = temp ; last . next = last ; return last ; } function addBegin ( last , data ) { if ( last == null ) return addToEmpty ( data ) ; let temp = new Node ( ) ; temp . data = data ; temp . next = last . next ; last . next = temp ; return last ; } function traverse ( last ) { let p ; if ( last == null ) { document . write ( " " ) ; return ; } p = last . next ; do { document . write ( p . data + " " ) ; p = p . next ; } while ( p != last . next ) ; document . write ( " " ) ; } function length ( last ) { let x = 0 ; if ( last == null ) return x ; let itr = last . next ; while ( itr . next != last . next ) { x ++ ; itr = itr . next ; } return ( x + 1 ) ; } function split ( last , k ) { let pass = new Node ( ) ; if ( last == null ) return last ; let newLast , itr = last ; for ( let i = 0 ; i < k ; i ++ ) { itr = itr . next ; } newLast = itr ; pass . next = itr . next ; newLast . next = last . next ; last . next = pass . next ; return newLast ; } let clist = null ; clist = addToEmpty ( clist , 12 ) ; clist = addBegin ( clist , 10 ) ; clist = addBegin ( clist , 8 ) ; clist = addBegin ( clist , 6 ) ; clist = addBegin ( clist , 4 ) ; clist = addBegin ( clist , 2 ) ; document . write ( " " ) ; traverse ( clist ) ; let k = 4 ; let clist2 = split ( clist , k ) document . write ( " " ) ; traverse ( clist2 ) ; traverse ( clist ) ;