Recursive selection sort for singly linked list | Swapping node links | A Linked list node ; function to swap nodes ' currX ' and ' currY ' in a linked list without swapping data ; make ' currY ' as new head ; adjust links ; Swap next pointers ; function to sort the linked list using recursive selection sort technique ; if there is only a single node ; ' min ' - pointer to store the node having minimum data value ; ' beforeMin ' - pointer to store node previous to ' min ' node ; traverse the list till the last node ; if true , then update ' min ' and ' beforeMin ' ; if ' min ' and ' head ' are not same , swap the head node with the ' min ' node ; recursively sort the remaining list ; function to sort the given linked list ; if list is empty ; sort the list using recursive selection sort technique ; function to insert a node at the beginning of the linked list ; allocate node ; put in the data ; link the old list to the new node ; move the head to povar to the new node ; function to prvar the linked list ; Driver code ; create linked list 10.12 .8 .4 .6 ; sort the linked list
class Node { constructor ( val ) { this . data = val ; this . next = null ; } } function swapNodes ( head_ref , currX , currY , prevY ) { head_ref = currY ; prevY . next = currX ; var temp = currY . next ; currY . next = currX . next ; currX . next = temp ; return head_ref ; } function recurSelectionSort ( head ) { if ( head . next == null ) return head ; var min = head ; var beforeMin = null ; var ptr ; for ( ptr = head ; ptr . next != null ; ptr = ptr . next ) { if ( ptr . next . data < min . data ) { min = ptr . next ; beforeMin = ptr ; } } if ( min != head ) head = swapNodes ( head , head , min , beforeMin ) ; head . next = recurSelectionSort ( head . next ) ; return head ; } function sort ( head_ref ) { if ( ( head_ref ) == null ) return null ; head_ref = recurSelectionSort ( head_ref ) ; return head_ref ; } function push ( head_ref , new_data ) { var new_node = new Node ( ) ; new_node . data = new_data ; new_node . next = ( head_ref ) ; ( head_ref ) = new_node ; return head_ref ; } function printList ( head ) { while ( head != null ) { document . write ( head . data + " " ) ; head = head . next ; } } var head = null ; head = push ( head , 6 ) ; head = push ( head , 4 ) ; head = push ( head , 8 ) ; head = push ( head , 12 ) ; head = push ( head , 10 ) ; document . write ( " " ) ; printList ( head ) ; head = sort ( head ) ; document . write ( " " ) ; printList ( head ) ;