Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
617 views
in Technique[技术] by (71.8m points)

java - Counting all the nodes in a Linked List

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...