Rearrange a given linked list in | Creating the structure for node javascript implementation ;  ; Function to print the list ; Function to rearrange ; we set left = null , when we reach stop condition , so no processing required after that ; Stop condition : odd case : left = right , even case : left . next = right ; stop condition , set null to left nodes ; even case ; odd case ; Drivers Code ; Print original list ; Modify the list ; Print modified list
class Node { constructor ( val ) { this . data = val ; this . next = null ; } } var left = null ; function printlist ( head ) { while ( head != null ) { document . write ( head . data + " " ) ; if ( head . next != null ) { document . write ( " " ) ; } head = head . next ; } document . write ( " " ) ; } function rearrange ( head ) { if ( head != null ) { left = head ; reorderListUtil ( left ) ; } } function reorderListUtil ( right ) { if ( right == null ) { return ; } reorderListUtil ( right . next ) ; if ( left == null ) { return ; } if ( left != right && left . next != right ) { var temp = left . next ; left . next = right ; right . next = temp ; left = temp ; } else { if ( left . next == right ) { left . next . next = null ; left = null ; } else { left . next = null ; left = null ; } } } var head = new Node ( 1 ) ; head . next = new Node ( 2 ) ; head . next . next = new Node ( 3 ) ; head . next . next . next = new Node ( 4 ) ; head . next . next . next . next = new Node ( 5 ) ; printlist ( head ) ; rearrange ( head ) ; printlist ( head ) ;