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

Assuming you have a singly linked list in C#, you can find the median by using the slow/fast pointer technique which is also commonly used for finding the middle element of a linked list. Here's how you can do it:

main.cs
public double FindMedian(LinkedList<int> list)
{
    if (list == null || list.Count == 0) // empty list
        return 0;

    var slow = list.First;
    var fast = list.First;

    while (fast != null && fast.Next != null)
    {
        slow = slow.Next;
        fast = fast.Next.Next;
    }

    if (fast == null) // even number of nodes in the list
        return (double)(slow.Value + slow.Previous.Value) / 2;

    // odd number of nodes in the list
    return (double)slow.Value;
}
488 chars
21 lines

Explanation:

  • We start by initializing two pointers, slow and fast, both pointing to the first node of the linked list.
  • We use the fast pointer to traverse the list at a rate of two nodes at a time, and the slow pointer to traverse the list at a rate of one node at a time.
  • When the fast pointer reaches the end of the list or the second last node in the list, the slow pointer will be pointing to the middle node of the list.
  • If the number of nodes in the list is even, we return the average of the values of the middle node and the node before it.
  • If the number of nodes in the list is odd, we simply return the value of the middle node.

Note: This implementation assumes that the linked list contains only int values. You can modify it to handle other data types by changing the generic type parameter of the LinkedList<T> class.

gistlibby LogSnag