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
You aren't counting the last node. When you get to the last element to be counted, n.next will be null, and so count is never incremented. You might instead try a loop like the following:
ListNode n = head;
for (ListNode n = head; n != null; n = n.next) {
count++;
}
Well that's because you are starting your count from 0, neglecting the first node.
Instead initialize count=1
;
I figured it out.
for (ListNode n = head; n != null; n = n.next)
n.next !=null was the error.
You want to loop until n == null. As it stands, you're stopping one short.
The end node will fail n.next != null
but it is part the the LinkedList, so you should consider that. It sounds like you simply have an indexing error.
try this
public int count() {
int count = 0;
for (ListNode n = head; n != null; n = n.next) {
count++;
}
return count;
}