Make middle node head in a linked list | Link list node ; * Function to get the middle and set at beginning of the linked list ; To traverse list nodes one by one ; To traverse list nodes by skipping one . ; To keep track of previous of middle ; for previous node of middle node ; move one node each time ; move two node each time ; set middle node at head ; To insert a node at the beginning of linked list . ; allocate node ; link the old list off the new node ; move the head to povar to the new node ; A function to prvar a given linked list ; Create a list of 5 nodes
class Node { constructor ( val ) { this . data = val ; this . next = null ; } } var head ; function setMiddleHead ( ) { if ( head == null ) return ; one_node = head ; two_node = head ; prev = null ; while ( two_node != null && two_node . next != null ) { prev = one_node ; two_node = two_node . next . next ; one_node = one_node . next ; } prev . next = prev . next . next ; one_node . next = head ; head = one_node ; } function push ( new_data ) { new_node = new Node ( new_data ) ; new_node . next = head ; head = new_node ; } function printList ( ptr ) { while ( ptr != null ) { document . write ( ptr . data + " " ) ; ptr = ptr . next ; } document . write ( " " ) ; } head = null ; var i ; for ( i = 5 ; i > 0 ; i -- ) push ( i ) ; document . write ( " " ) ; printList ( head ) ; setMiddleHead ( ) ; document . write ( " " ) ; printList ( head ) ;