Sort the linked list in the order of elements appearing in the array | Linked list node ; Function to insert a node at the beginning of the linked list ; function to print the linked list ; Function that sort list in order of apperaing elements in an array ; Store frequencies of elements in a hash table . ; One by one put elements in lis according to their appearance in array ; Update ' frequency ' nodes with value equal to arr [ i ] ; Modify list data as element appear in an array ; Driver Code ; creating the linked list ; Function call to sort the list in order elements are apperaing in an array ; print the modified linked list
class Node : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . data = 0 NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def push ( head_ref , new_data ) : NEW_LINE INDENT new_node = Node ( ) NEW_LINE new_node . data = new_data NEW_LINE new_node . next = head_ref NEW_LINE head_ref = new_node NEW_LINE return head_ref NEW_LINE DEDENT def printList ( head ) : NEW_LINE INDENT while ( head != None ) : NEW_LINE INDENT print ( head . data , end = " - > " ) NEW_LINE head = head . next NEW_LINE DEDENT DEDENT def sortlist ( arr , N , head ) : NEW_LINE INDENT hash = dict ( ) NEW_LINE temp = head NEW_LINE while ( temp != None ) : NEW_LINE INDENT hash [ temp . data ] = hash . get ( temp . data , 0 ) + 1 NEW_LINE temp = temp . next NEW_LINE DEDENT temp = head NEW_LINE for i in range ( N ) : NEW_LINE INDENT frequency = hash . get ( arr [ i ] , 0 ) NEW_LINE while ( frequency > 0 ) : NEW_LINE INDENT frequency = frequency - 1 NEW_LINE temp . data = arr [ i ] NEW_LINE temp = temp . next NEW_LINE DEDENT DEDENT DEDENT head = None NEW_LINE arr = [ 5 , 1 , 3 , 2 , 8 ] NEW_LINE N = len ( arr ) NEW_LINE head = push ( head , 3 ) NEW_LINE head = push ( head , 2 ) NEW_LINE head = push ( head , 5 ) NEW_LINE head = push ( head , 8 ) NEW_LINE head = push ( head , 5 ) NEW_LINE head = push ( head , 2 ) NEW_LINE head = push ( head , 1 ) NEW_LINE sortlist ( arr , N , head ) NEW_LINE print ( " Sorted ▁ List : " ) NEW_LINE printList ( head ) NEW_LINE