Swap nodes in a linked list without swapping data | JavaScript program to swap two given nodes of a linked list ; head of list ; Function to swap Nodes x and y in linked list by changing links ; Nothing to do if x and y are same ; Search for x ( keep track of prevX and CurrX ) ; Search for y ( keep track of prevY and currY ) ; If either x or y is not present , nothing to do ; If x is not head of linked list ; make y the new head ; If y is not head of linked list ; make x the new head ; Swap next pointers ; Function to add Node at beginning of list . ; 1. alloc the Node and put the data ; 2. Make next of new Node as head ; 3. Move the head to point to new Node ; This function prints contents of linked list starting from the given Node ; The constructed linked list is : 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7
class Node { constructor ( val ) { this . data = val ; this . next = null ; } } var head ; function swapNodes ( x , y ) { if ( x == y ) return ; var prevX = null , currX = head ; while ( currX != null && currX . data != x ) { prevX = currX ; currX = currX . next ; } var prevY = null , currY = head ; while ( currY != null && currY . data != y ) { prevY = currY ; currY = currY . next ; } if ( currX == null currY == null ) return ; if ( prevX != null ) prevX . next = currY ; else head = currY ; if ( prevY != null ) prevY . next = currX ; else head = currX ; var temp = currX . next ; currX . next = currY . next ; currY . next = temp ; } function push ( new_data ) { var new_Node = new Node ( new_data ) ; new_Node . next = head ; head = new_Node ; } function printList ( ) { var tNode = head ; while ( tNode != null ) { document . write ( tNode . data + " " ) ; tNode = tNode . next ; } } push ( 7 ) ; push ( 6 ) ; push ( 5 ) ; push ( 4 ) ; push ( 3 ) ; push ( 2 ) ; push ( 1 ) ; document . write ( " " ) ; printList ( ) ; swapNodes ( 4 , 3 ) ; document . write ( " " ) ; printList ( ) ;