The linked list is a linear data structure for storing data. A lot of interview questions are asked on the linked list. In this post, I will show you how to count the number of nodes in the linked list.
public class LinkedList
{
private class Node
{
public int Data { get; set; }
public Node Next { get; set; }
public Node(int data)
{
Data = data;
Next = null;
}
}
private Node _head;
private int _count = 0;
public void Add(int data)
{
var newNode = new Node(data);
if (_head == null)
_head = newNode;
else
{
newNode.Next = _head;
_head = newNode;
}
}
public int Count()
{
if (_head == null)
return _count;
for (Node current = _head; current != null; current = current.Next)
{
_count++;
}
return _count;
}
}