Sort the linked list in the order of elements appearing in the array | Efficient JAVA program to sort given list in order elements are appearing in an 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
import java . util . * ; class GFG { static class Node { int data ; Node next ; } ; static Node push ( Node head_ref , int new_data ) { Node new_node = new Node ( ) ; new_node . data = new_data ; new_node . next = head_ref ; head_ref = new_node ; return head_ref ; } static void printList ( Node head ) { while ( head != null ) { System . out . print ( head . data + " - > " ) ; head = head . next ; } } static void sortlist ( int arr [ ] , int N , Node head ) { HashMap < Integer , Integer > hash = new HashMap < Integer , Integer > ( ) ; Node temp = head ; while ( temp != null ) { if ( hash . containsKey ( temp . data ) ) hash . put ( temp . data , hash . get ( temp . data ) + 1 ) ; else hash . put ( temp . data , 1 ) ; temp = temp . next ; } temp = head ; for ( int i = 0 ; i < N ; i ++ ) { int frequency = hash . get ( arr [ i ] ) ; while ( frequency -- > 0 ) { temp . data = arr [ i ] ; temp = temp . next ; } } } public static void main ( String [ ] args ) { Node head = null ; int arr [ ] = { 5 , 1 , 3 , 2 , 8 } ; int N = arr . length ; head = push ( head , 3 ) ; head = push ( head , 2 ) ; head = push ( head , 5 ) ; head = push ( head , 8 ) ; head = push ( head , 5 ) ; head = push ( head , 2 ) ; head = push ( head , 1 ) ; sortlist ( arr , N , head ) ; System . out . print ( " Sorted ▁ List : " + "NEW_LINE"); printList ( head ) ; } }