find the smallest node in a linked list in csharp

To find the smallest node in a linked list, first we have to traverse through the linked list and compare the data of each node with the smallest node seen so far. Here's the C# code to accomplish this:

main.cs
public Node FindSmallestNode(Node head)
{
    if (head == null)   // Check if the list is empty
        return null;

    Node current = head;
    Node smallest = head;

    while (current != null)
    {
        if (current.Data < smallest.Data)  // Compare data of current node with smallest node so far
            smallest = current;

        current = current.Next;  // Move to the next node
    }

    return smallest;
}
426 chars
19 lines

In this code, we initialize two variables current and smallest to the head of the linked list. We then traverse through the linked list using a while loop and compare the data of each node with the data of the smallest node seen so far. If we find a node with smaller data, we set the smallest variable to that node. Finally, we return the smallest variable, which now contains the smallest node in the linked list.

gistlibby LogSnag