Rotate a Linked List | Link list node ; This function rotates a linked list counter - clockwise and updates the head . The function assumes that k is smaller than size of linked list . ; Let us understand the below code for example k = 4 and list = 10.20 . 30.40 .50 . 60. ; Traverse till the end . ; traverse the linked list to k - 1 position which will be last element for rotated array . ; update the head_ref and last element pointer to null ; Function to push a node ; allocate node ; put in the data ; link the old list off the new node ; move the head to povar to the new node ; Function to prvar linked list ; create a list 10.20 . 30.40 .50 . 60
class Node { constructor ( ) { this . data = 0 ; this . next = null ; } } var head = null ; function rotate ( k ) { if ( k == 0 ) return ; var current = head ; while ( current . next != null ) current = current . next ; current . next = head ; current = head ; for ( i = 0 ; i < k - 1 ; i ++ ) current = current . next ; head = current . next ; current . next = null ; } function push ( new_data ) { var new_node = new Node ( ) ; new_node . data = new_data ; new_node . next = head ; head = new_node ; } function printList ( node ) { while ( node != null ) { document . write ( node . data + " " ) ; node = node . next ; } } for ( i = 60 ; i > 0 ; i -= 10 ) push ( i ) ; document . write ( " " ) ; printList ( head ) ; rotate ( 4 ) ; document . write ( " " ) ; printList ( head ) ;