find the mode of all nodes in a linked list in python

One approach to find the mode of all nodes in a linked list is as follows:

  1. Traverse the linked list and create a list of all the node values.
  2. Use the collections module to count the occurrences of each distinct value in the list.
  3. Find the maximum count using the max function.
  4. Filter the values in the count dictionary to find all values that occur the maximum number of times.
  5. Return the resulting list of mode values.

Here's the code:

main.py
import collections
import statistics

def find_mode_of_linked_list(head):
    # create a list of all the node values
    node_values = []
    current = head
    while current is not None:
        node_values.append(current.val)
        current = current.next
    
    # count the occurrences of each distinct value
    counts = collections.Counter(node_values)
    
    # find the maximum count
    max_count = max(counts.values())
    
    # filter the values that occur the maximum number of times
    mode_values = [value for value, count in counts.items() if count == max_count]
    
    return mode_values
611 chars
22 lines

Note that this code assumes that the linked list is implemented using a Node class with val and next attributes. The statistics module is imported but not used, it is left as a potential alternative.

gistlibby LogSnag