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

To find the mode of all nodes in a linked list, we need to first count the occurrence of each value in the list. We can use a hash table to maintain a count of each value in the list. Once we have the count, we can simply find the value with the highest count to determine the mode.

Here's the C# code to find the mode of all nodes in a linked list:

main.cs
using System.Collections.Generic;

public class Node
{
    public int Value { get; set; }
    public Node Next { get; set; }
}

public static int FindMode(Node head)
{
    var freq = new Dictionary<int, int>();

    Node curr = head;

    while (curr != null)
    {
        if (freq.ContainsKey(curr.Value))
        {
            freq[curr.Value]++;
        }
        else
        {
            freq[curr.Value] = 1;
        }

        curr = curr.Next;
    }

    int mode = 0;
    int maxFreq = 0;

    foreach (KeyValuePair<int, int> item in freq)
    {
        if (item.Value > maxFreq)
        {
            maxFreq = item.Value;
            mode = item.Key;
        }
    }

    return mode;
}
700 chars
43 lines

In the code above, we create a hash table freq to store the count of each value in the linked list. We then traverse the linked list to count the occurrence of each value using the hash table.

Finally, we traverse through the hash table and find the key with the highest value to determine the mode of the linked list. The mode is stored in the variable mode and returned by the function.

gistlibby LogSnag