find the length of a linked list in csharp

To find the length of a linked list in C#, we can iterate through the list and count the number of nodes. Here's an implementation:

main.cs
public int GetLinkedListLength(ListNode head)
{
    int count = 0;
    ListNode current = head;
    
    while(current != null)
    {
        count++;
        current = current.next;
    }
    
    return count;
}
214 chars
14 lines

Explanation:

  • We declare a count variable to keep track of the number of nodes we've counted so far
  • We start by setting current to the head of the linked list
  • While current is not null (i.e. there are still nodes to count), we increment count and move current to the next node in the list
  • Once all nodes have been counted, we return the final value of count

Note that this implementation assumes that each node in the linked list has a next field pointing to the next node in the sequence. If you're using a different implementation of a linked list, the exact code may vary.

gistlibby LogSnag