text: Alternate Odd and Even Nodes in a Singly Linked List | class node ; A utility function to print linked list ; Function to create newNode in a linkedlist ; Function to insert at beginning ; Function to rearrange the odd and even nodes ; Odd Value in Even Position Add pointer to current node in odd stack ; Even Value in Odd Position Add pointer to current node in even stack ; Swap Data at the top of two stacks ; Driver code
code: class Node { constructor ( ) { this . data = 0 ; this . next = null ; } } function printList ( node ) { while ( node != null ) { document . write ( node . data + " " ) ; node = node . next ; } document . write ( ) ; } function newNode ( key ) { var temp = new Node ( ) ; temp . data = key ; temp . next = null ; return temp ; } function insertBeg ( head , val ) { var temp = newNode ( val ) ; temp . next = head ; head = temp ; return head ; } function rearrangeOddEven ( head ) { var odd = [ ] ; var even = [ ] ; var i = 1 ; while ( head != null ) { if ( head . data % 2 != 0 && i % 2 == 0 ) { odd . push ( head ) ; } else if ( head . data % 2 == 0 && i % 2 != 0 ) { even . push ( head ) ; } head = head . next ; i ++ ; } while ( odd . length > 0 && even . length > 0 ) { var k = odd [ odd . length - 1 ] . data ; odd [ odd . length - 1 ] . data = even [ even . length - 1 ] . data ; even [ even . length - 1 ] . data = k ; odd . pop ( ) ; even . pop ( ) ; } } var head = newNode ( 8 ) ; head = insertBeg ( head , 7 ) ; head = insertBeg ( head , 6 ) ; head = insertBeg ( head , 5 ) ; head = insertBeg ( head , 3 ) ; head = insertBeg ( head , 2 ) ; head = insertBeg ( head , 1 ) ; document . write ( " " ) ; printList ( head ) ; rearrangeOddEven ( head ) ; document . write ( " " + " " ) ; printList ( head ) ;