Sort the linked list in the order of elements appearing in the array

Given an array of size N and a Linked List where elements will be from the array but can also be duplicated, sort the linked list in the order, elements are appearing in the array. It may be assumed that the array covers all elements of the linked list.
arr[] =Â
Â
list =Â
Sorted list =Â
Asked in AmazonÂ
Â
First, make a hash table that stores the frequencies of elements in linked list. Then, simply traverse list and for each element of arr[i] check the frequency in the hashtable and modify the data of list by arr[i] element upto its frequency and at last Print the list.Â
Implementation:
C++
// Efficient CPP program to sort given list in order// elements are appearing in an array#include <bits/stdc++.h>using namespace std;Â
// Linked list nodestruct Node {Â Â Â Â int data;Â Â Â Â struct Node* next;};Â
// function prototype for printing the listvoid printList(struct Node*);Â
// Function to insert a node at the// beginning of the linked listvoid push(struct Node** head_ref, int new_data){Â Â Â Â struct Node* new_node = new Node;Â Â Â Â new_node -> data = new_data;Â Â Â Â new_node -> next = *head_ref;Â Â Â Â *head_ref = new_node;}Â
// function to print the linked listvoid printList(struct Node* head){Â Â Â Â while (head != NULL) {Â Â Â Â Â Â Â Â cout << head -> data << " -> ";Â Â Â Â Â Â Â Â head = head -> next;Â Â Â Â }}Â
// Function that sort list in order of appearing// elements in an arrayvoid sortlist(int arr[], int N, struct Node* head){    // Store frequencies of elements in a    // hash table.    unordered_map<int, int> hash;    struct Node* temp = head;    while (temp) {               hash[temp -> data]++;        temp = temp -> next;    }Â
    temp = head;      // One by one put elements in list according    // to their appearance in array    for (int i = 0; i < N; i++) {       Â
        // Update 'frequency' nodes with value         // equal to arr[i]        int frequency = hash[arr[i]];        while (frequency--) {Â
            // Modify list data as element             // appear in an array            temp -> data = arr[i];            temp = temp -> next;        }    }}Â
// Driver Codeint main(){Â Â Â Â struct Node* head = NULL;Â Â Â Â int arr[] = { 5, 1, 3, 2, 8 };Â Â Â Â int N = sizeof(arr) / sizeof(arr[0]);Â
    // creating the linked list    push(&head, 3);    push(&head, 2);    push(&head, 5);    push(&head, 8);    push(&head, 5);    push(&head, 2);    push(&head, 1);Â
    // Function call to sort the list in order    // elements are appearing in an array    sortlist(arr, N, head);Â
    // print the modified linked list    cout << "Sorted List:" << endl;    printList(head);    return 0;} |
Java
// Efficient JAVA program to sort given list in order// elements are appearing in an arrayimport java.util.*;Â
class GFG{Â
// Linked list nodestatic class Node{Â Â Â Â int data;Â Â Â Â Node next;};Â
// Function to insert a node at the// beginning of the linked liststatic 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;}Â
// function to print the linked liststatic void printList(Node head){Â Â Â Â while (head != null)Â Â Â Â {Â Â Â Â Â Â Â Â System.out.print(head.data+ "->");Â Â Â Â Â Â Â Â head = head.next;Â Â Â Â }}Â
// Function that sort list in order of appearing// elements in an arraystatic void sortlist(int arr[], int N, Node head){    // Store frequencies of elements in a    // hash table.    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;Â
    // One by one put elements in list according    // to their appearance in array    for (int i = 0; i < N; i++)     {    Â
        // Update 'frequency' nodes with value         // equal to arr[i]        int frequency = hash.get(arr[i]);        while (frequency-->0)         {Â
            // Modify list data as element             // appear in an array            temp.data = arr[i];            temp = temp.next;        }    }}Â
// Driver Codepublic static void main(String[] args){Â Â Â Â Node head = null;Â Â Â Â int arr[] = { 5, 1, 3, 2, 8 };Â Â Â Â int N = arr.length;Â
    // creating the linked list    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);Â
    // Function call to sort the list in order    // elements are appearing in an array    sortlist(arr, N, head);Â
    // print the modified linked list    System.out.print("Sorted List:" +"\n");    printList(head);}}Â
// This code is contributed by PrinciRaj1992 |
Python3
# Efficient Python3 program to sort given list in order# elements are appearing in an arrayÂ
# Linked list nodeclass Node:Â Â Â Â def __init__(self):Â Â Â Â Â Â Â Â self.data = 0Â Â Â Â Â Â Â Â self.next = NoneÂ
# Function to insert a node at the# beginning of the linked listdef push( head_ref, new_data):Â
    new_node = Node()    new_node.data = new_data    new_node.next = head_ref    head_ref = new_node    return head_refÂ
# function to print the linked listdef printList( head):Â
    while (head != None):             print(head.data, end = "->")        head = head.next     # Function that sort list in order of appearing# elements in an arraydef sortlist( arr, N, head):Â
    # Store frequencies of elements in a    # hash table.    hash = dict()    temp = head    while (temp != None) :             hash[temp.data] = hash.get(temp.data, 0) + 1        temp = temp.next         temp = headÂ
    # One by one put elements in list according    # to their appearance in array    for i in range(N):                  # Update 'frequency' nodes with value         # equal to arr[i]        frequency = hash.get(arr[i],0)                 while (frequency > 0) :                     frequency= frequency-1            # Modify list data as element             # appear in an array            temp.data = arr[i]            temp = temp.next         # Driver CodeÂ
head = Nonearr = [5, 1, 3, 2, 8 ]N = len(arr)Â
# creating the linked listhead = 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)Â
# Function call to sort the list in order# elements are appearing in an arraysortlist(arr, N, head)Â
# print the modified linked listprint("Sorted List:" )printList(head)Â
Â
# This code is contributed by Arnab Kundu |
C#
// Efficient C# program to sort given list in order// elements are appearing in an arrayusing System;using System.Collections.Generic;Â
class GFG{Â
// Linked list nodepublic class Node{Â Â Â Â public int data;Â Â Â Â public Node next;};Â
// Function to insert a node at the// beginning of the linked liststatic 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;}Â
// function to print the linked liststatic void printList(Node head){Â Â Â Â while (head != null)Â Â Â Â {Â Â Â Â Â Â Â Â Console.Write(head.data + "->");Â Â Â Â Â Â Â Â head = head.next;Â Â Â Â }}Â
// Function that sort list in order of appearing// elements in an arraystatic void sortlist(int []arr, int N, Node head){    // Store frequencies of elements in a    // hash table.    Dictionary<int,                int> hash = new Dictionary<int,                                           int>();    Node temp = head;    while (temp != null)     {         if(hash.ContainsKey(temp.data))            hash[temp.data] = hash[temp.data] + 1;        else            hash.Add(temp.data, 1);        temp = temp.next;    }    temp = head;Â
    // One by one put elements in list according    // to their appearance in array    for (int i = 0; i < N; i++)     {    Â
        // Update 'frequency' nodes with value         // equal to arr[i]        int frequency = hash[arr[i]];        while (frequency-->0)         {Â
            // Modify list data as element             // appear in an array            temp.data = arr[i];            temp = temp.next;        }    }}Â
// Driver Codepublic static void Main(String[] args){Â Â Â Â Node head = null;Â Â Â Â int []arr = { 5, 1, 3, 2, 8 };Â Â Â Â int N = arr.Length;Â
    // creating the linked list    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);Â
    // Function call to sort the list in order    // elements are appearing in an array    sortlist(arr, N, head);Â
    // print the modified linked list    Console.Write("Sorted List:" + "\n");    printList(head);}}Â
// This code is contributed by 29AjayKumar |
Javascript
<script>Â
// Efficient Javascript program to sort given list in order// elements are appearing in an arrayÂ
// Linked list nodeclass Node{Â Â Â Â constructor()Â Â Â Â {Â Â Â Â Â Â Â Â this.data = 0;Â Â Â Â Â Â Â Â this.next = null;Â Â Â Â }};Â
// Function to insert a node at the// beginning of the linked listfunction 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 to print the linked listfunction printList(head){Â Â Â Â while (head != null)Â Â Â Â {Â Â Â Â Â Â Â Â document.write(head.data + " -> ");Â Â Â Â Â Â Â Â head = head.next;Â Â Â Â }}Â
// Function that sort list in order of appearing// elements in an arrayfunction sortlist( arr, N, head){    // Store frequencies of elements in a    // hash table.    var hash = new Map();    var temp = head;    while (temp != null)     {         if(hash.has(temp.data))            hash.set(temp.data, hash.get(temp.data)+1);        else            hash.set(temp.data, 1);        temp = temp.next;    }    temp = head;Â
    // One by one put elements in list according    // to their appearance in array    for (var i = 0; i < N; i++)     {    Â
        // Update 'frequency' nodes with value         // equal to arr[i]        var frequency = hash.get(arr[i]);        while (frequency-->0)         {Â
            // Modify list data as element             // appear in an array            temp.data = arr[i];            temp = temp.next;        }    }}Â
// Driver Codevar head = null;var arr = [5, 1, 3, 2, 8];var N = arr.length;// creating the linked listhead = 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);// Function call to sort the list in order// elements are appearing in an arraysortlist(arr, N, head);// print the modified linked listdocument.write("Sorted List:" + "<br>");printList(head);Â
Â
</script> |
Output
Sorted List: 5 -> 5 -> 1 -> 3 -> 2 -> 2 -> 8 ->
Time Complexity: O(n2).
Auxiliary Space: O(n)
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!




