Rearrange a Linked List in Zig | Node class ; Prvar Linked List ; Swap both nodes ; Rearrange the linked list in zig zag way ; Driver Code ; 0 means the current element should be smaller than the next
class Node { constructor ( val ) { this . data = val ; this . next = null ; } } var head ; function printLL ( ) { var t = head ; while ( t != null ) { document . write ( t . data + " " ) ; t = t . next ; } document . write ( ) ; } function swap ( a , b ) { if ( a == null b == null ) return ; var temp = a . data ; a . data = b . data ; b . data = temp ; } function zigZag ( node , flag ) { if ( node == null node . next == null ) { return node ; } if ( flag == 0 ) { if ( node . data > node . next . data ) { swap ( node , node . next ) ; } return zigZag ( node . next , 1 ) ; } else { if ( node . data < node . next . data ) { swap ( node , node . next ) ; } return zigZag ( node . next , 0 ) ; } } head = new Node ( 11 ) ; head . next = new Node ( 15 ) ; head . next . next = new Node ( 20 ) ; head . next . next . next = new Node ( 5 ) ; head . next . next . next . next = new Node ( 10 ) ; printLL ( ) ; var flag = 0 ; zigZag ( head , flag ) ; document . write ( " " ) ; printLL ( ) ;