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;
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…