问题
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;
}
}
回答1:
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.
回答2:
I figured it out.
for (ListNode n = head; n != null; n = n.next)
n.next !=null was the error.
回答3:
You want to loop until n == null. As it stands, you're stopping one short.
回答4:
try this
public int count() {
int count = 0;
for (ListNode n = head; n != null; n = n.next) {
count++;
}
return count;
}
回答5:
Well that's because you are starting your count from 0, neglecting the first node.
Instead initialize count=1
;
回答6:
public int count() {
int count = 0;
for (ListNode n = head; n != null; n = n.next) {
count++;
}
return count;
}
回答7:
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++;
}
回答8:
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.)
回答9:
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;
来源:https://stackoverflow.com/questions/22086128/counting-all-the-nodes-in-a-linked-list