我正在尝试编写一个简单的方法来计算链表中的所有节点。我知道链接列表中有 7 个项目,但它只返回其中的 6 个。
这是我的方法
public int count() {
int count = 0;
for (ListNode n = head; n.next != null; n = n.next) {
count++;
}
return count;
}
这是我的 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;
}
}
最佳答案
结束节点将失败 n.next != null
但它是 LinkedList 的一部分,因此您应该考虑这一点。听起来您只是遇到了索引错误。
关于java - 计算链表中的所有节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22086128/