I\'m trying to write a simple method to count all the nodes in the linked list. I know there are 7 items in the linked list, but it is returning just 6 of them.
Her
n.next != null
Is your problem. Change it to n!=null
Example :
List : 1--> 2 -->3--> 4-->null
Count : 1--> 2-->3-->here n=4 and n.next=null. So, your loop will break and count will be 3 (i.e; the last node will not be counted.)
You should check for null first. If not 0, then set 'counter = 1' before you loop through it.
if (_first == null) return 0;
int count = 1;
for (ListNode n = _first; n.Next != null; n = n.Next)
{
count++;
}
return count;
public int count() {
int count = 0;
for (ListNode n = head; n != null; n = n.next) {
count++;
}
return count;
}