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

To find the average of all nodes in a linked list in C#, we need to traverse the entire linked list and compute the sum of all nodes' values. Then, we can divide the sum by the number of nodes to get the average value.

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

main.cs
public static double FindAverage(LinkedList<int> list)
{
    double sum = 0;
    int count = 0;

    foreach (int val in list)
    {
        sum += val;
        count++;
    }

    return sum / count;
}
203 chars
14 lines

In the above implementation, we use a LinkedList<int> to represent the linked list. We initialize two variables sum and count to 0 to keep track of the sum of all node values and the number of nodes in the list. We then loop through each node in the list and accumulate its value in sum, and increment count by 1.

Finally, we compute the average by dividing sum by count and return the result as a double.

We can call the FindAverage method as shown below:

main.cs
LinkedList<int> list = new LinkedList<int>();
list.AddLast(1);
list.AddLast(2);
list.AddLast(3);

double average = FindAverage(list);
Console.WriteLine("Average: " + average); // Output: 2
189 chars
8 lines

In this example, we create a linked list with three nodes containing the values 1, 2, and 3. We then call the FindAverage method passing the linked list as an argument. Finally, we print the average value 2 to the console using Console.WriteLine().

gistlibby LogSnag