15.9k views
3 votes
In the following, you are given a given singly linked list. You are asked to save unique nodes in decreasing order of their frequency in the list. You cannot create new node in this or change values of existing nodes.

Sample input: For example, you have this linked list.
L1: 2−>100−>12−>5−>6−>5−>2−>1−>5
If you run thisfunction named L1.unique(). Then, L1.print() should display :
L1: 5−>2−>100−>12−>1−>6
Explanation: As 5 occurred 3 times, 2 occurred 2 times, 100 occurred 1 time, 12 occurred 1 time, 1 occurred 1 time and 6 occurred 1 time. So, they exist uniquely in order of their decreasing frequencies and L1 should be set as L1: 5−>2−>100−>12−>1−>6.

User EK Chhuon
by
8.1k points

1 Answer

1 vote

Final answer:

To save unique nodes in a linked list based on their frequency, we can use a hashmap and a priority queue. First, count the frequency of each node using a hashmap. Then, create a priority queue to sort the nodes based on their frequency. Finally, update the linked list with the unique nodes in the desired order.

Step-by-step explanation:

To save unique nodes in decreasing order of their frequency in a singly linked list, we can use a hashmap to count the frequency of each node. Then, we can create a priority queue that sorts nodes based on their frequency in decreasing order. Finally, we can iterate through the priority queue and update the linked list with the unique nodes in the desired order.

User Augustorf
by
7.3k points