Bird
Raised Fist0
DSA C#programming

Get Length of Linked List in DSA C#

Choose your learning style10 modes available
Mental Model
Count how many nodes are in the linked list by moving from the start to the end, one node at a time.
Analogy: Imagine counting people standing in a line by walking from the first person to the last, counting each person you pass.
head -> 1 -> 2 -> 3 -> null
Dry Run Walkthrough
Input: list: 1 -> 2 -> 3 -> null
Goal: Find how many nodes are in the list
Step 1: start at head node with value 1
[curr->1] -> 2 -> 3 -> null
Why: We begin counting from the first node
Step 2: move to next node with value 2, count 2 nodes so far
1 -> [curr->2] -> 3 -> null
Why: We count each node as we move forward
Step 3: move to next node with value 3, count 3 nodes so far
1 -> 2 -> [curr->3] -> null
Why: Continue counting until no more nodes
Step 4: move to next which is null, stop counting
1 -> 2 -> 3 -> [curr->null]
Why: Reached end of list, counting complete
Result:
1 -> 2 -> 3 -> null
Length = 3
Annotated Code
DSA C#
using System;

public class Node
{
    public int data;
    public Node next;

    public Node(int data)
    {
        this.data = data;
        this.next = null;
    }
}

public class LinkedList
{
    public Node head;

    public int GetLength()
    {
        int count = 0;
        Node curr = head;
        while (curr != null)
        {
            count++; // increment count for current node
            curr = curr.next; // move to next node
        }
        return count;
    }
}

public class Program
{
    public static void Main()
    {
        LinkedList list = new LinkedList();
        list.head = new Node(1);
        list.head.next = new Node(2);
        list.head.next.next = new Node(3);

        int length = list.GetLength();
        Console.WriteLine("Length = " + length);
    }
}
int count = 0;
initialize count to zero before counting nodes
Node curr = head;
start traversal from head node
while (curr != null)
continue until end of list (null)
count++; // increment count for current node
count each node visited
curr = curr.next; // move to next node
advance to next node to continue counting
return count;
return total number of nodes counted
OutputSuccess
Length = 3
Complexity Analysis
Time: O(n) because we visit each of the n nodes once to count them
Space: O(1) because we only use a few variables regardless of list size
vs Alternative: This is optimal compared to approaches that might try to store nodes or use recursion, which could use more space
Edge Cases
empty list (head is null)
count remains zero and function returns 0
DSA C#
while (curr != null)
single node list
count increments once and returns 1
DSA C#
while (curr != null)
When to Use This Pattern
When asked to find how many elements are in a linked list, use a simple traversal counting nodes until you reach the end.
Common Mistakes
Mistake: Forgetting to move to the next node inside the loop, causing an infinite loop
Fix: Add 'curr = curr.next;' inside the while loop to advance the pointer
Mistake: Initializing count inside the loop instead of before it
Fix: Initialize count before the loop to accumulate total count correctly
Summary
Counts the number of nodes in a linked list by traversing it once.
Use when you need to know the size of a linked list.
The key is to move through each node and count until you reach the end.

Practice

(1/5)
1. What does the length of a linked list represent?
easy
A. The sum of all node values
B. The value of the first node
C. The memory size of the linked list
D. The number of nodes in the linked list

Solution

  1. Step 1: Understand linked list structure

    A linked list is made of nodes connected one after another.
  2. Step 2: Define length meaning

    The length is how many nodes are present in the list.
  3. Final Answer:

    The number of nodes in the linked list -> Option D
  4. Quick Check:

    Length = count of nodes [OK]
Hint: Count nodes to get length quickly [OK]
Common Mistakes:
  • Confusing length with node values
  • Thinking length is memory size
  • Assuming length is sum of values
2. Which of the following C# code snippets correctly initializes a variable to count the length of a linked list?
easy
A. int length = 0;
B. int length = null;
C. string length = "0";
D. bool length = false;

Solution

  1. Step 1: Identify correct data type for counting

    Length is a number, so it should be an integer type.
  2. Step 2: Check initialization value

    Start counting from zero before traversing nodes.
  3. Final Answer:

    int length = 0; -> Option A
  4. Quick Check:

    Use int and start at 0 [OK]
Hint: Use int zero to start counting length [OK]
Common Mistakes:
  • Using null for int variable
  • Using string instead of int
  • Using bool for counting
3. What will be the output of the following C# code?
public class Node {
  public int data;
  public Node next;
  public Node(int d) { data = d; next = null; }
}

public class LinkedList {
  public Node head;
  public int GetLength() {
    int count = 0;
    Node current = head;
    while (current != null) {
      count++;
      current = current.next;
    }
    return count;
  }
}

LinkedList list = new LinkedList();
list.head = new Node(5);
list.head.next = new Node(10);
list.head.next.next = new Node(15);
Console.WriteLine(list.GetLength());
medium
A. 0
B. 2
C. 3
D. Error

Solution

  1. Step 1: Count nodes in the linked list

    Nodes are 5 -> 10 -> 15, total 3 nodes.
  2. Step 2: Trace GetLength method

    Loop increments count for each node until null is reached.
  3. Final Answer:

    3 -> Option C
  4. Quick Check:

    3 nodes counted = 3 [OK]
Hint: Count each node until null to get length [OK]
Common Mistakes:
  • Counting only head node
  • Returning zero without counting
  • Confusing next pointer with data
4. Identify the error in this C# method to get linked list length:
public int GetLength() {
  int count = 0;
  Node current = head;
  while (current.next != null) {
    count++;
    current = current.next;
  }
  return count;
}
medium
A. It misses counting the last node
B. It causes infinite loop
C. It returns count plus one extra
D. It throws null reference exception

Solution

  1. Step 1: Analyze loop condition

    Loop runs while current.next is not null, so last node is skipped.
  2. Step 2: Understand counting effect

    Count increments only for nodes before last, missing last node.
  3. Final Answer:

    It misses counting the last node -> Option A
  4. Quick Check:

    Loop condition excludes last node [OK]
Hint: Use current != null to include last node [OK]
Common Mistakes:
  • Using current.next != null instead of current != null
  • Not incrementing count for last node
  • Assuming loop covers all nodes
5. Given a linked list where each node contains an integer, how would you modify the length calculation to count only nodes with even values?
public int GetEvenLength() {
  int count = 0;
  Node current = head;
  while (current != null) {
    // Your code here
    current = current.next;
  }
  return count;
}
hard
A. Add count++ unconditionally inside the loop
B. Add if (current.data % 2 == 0) count++; inside the loop
C. Add if (current.data % 2 != 0) count++; inside the loop
D. Return head.data instead of count

Solution

  1. Step 1: Check node value for evenness

    Use modulo operator to test if data is even (data % 2 == 0).
  2. Step 2: Increment count only if node is even

    Inside loop, increment count only when condition is true.
  3. Final Answer:

    Add if (current.data % 2 == 0) count++; inside the loop -> Option B
  4. Quick Check:

    Count only even nodes [OK]
Hint: Use modulo to filter even nodes before counting [OK]
Common Mistakes:
  • Counting all nodes without condition
  • Counting odd nodes instead of even
  • Returning node data instead of count
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard