Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
582 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...