Reputation: 327
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.
Here is my method
public int count() {
int count = 0;
for (ListNode n = head; n.next != null; n = n.next) {
count++;
}
return count;
}
And here is my ListNode.java
public class ListNode {
String name; // a name in the list
ListNode next; // the next node in the list
ListNode prev; // the previous node in the list
/**
* Constructor with just a name. This form would be most useful when
* starting a list.
*/
public ListNode(String name) {
this.name = name;
next = null;
prev = null;
}
/**
* Constructor with a name and a reference to the previous list node. This
* form would be most useful when adding to the end of a list.
*/
public ListNode(String name, ListNode node) {
this.name = name;
next = null;
prev = node;
}
}
Upvotes: 1
Views: 15972
Reputation: 1
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;
Upvotes: 0
Reputation: 534
try this
public int count() {
int count = 0;
for (ListNode n = head; n != null; n = n.next) {
count++;
}
return count;
}
Upvotes: 2
Reputation: 36304
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.)
Upvotes: 0
Reputation: 5314
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.
Upvotes: 3
Reputation: 327
I figured it out.
for (ListNode n = head; n != null; n = n.next)
n.next !=null was the error.
Upvotes: 2
Reputation: 796
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++;
}
Upvotes: 0
Reputation: 54682
public int count() {
int count = 0;
for (ListNode n = head; n != null; n = n.next) {
count++;
}
return count;
}
Upvotes: 0
Reputation: 6233
You want to loop until n == null. As it stands, you're stopping one short.
Upvotes: 1
Reputation: 2045
Well that's because you are starting your count from 0, neglecting the first node.
Instead initialize count=1
;
Upvotes: 0