计算链接列表中的所有节点

我正在尝试编写一个简单的方法来计算链表中的所有节点。 我知道链表中有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的一部分,所以你应该考虑这一点。 听起来你只是有一个索引错误。

我想到了。

 for (ListNode n = head; n != null; n = n.next) 

n.next!= null是错误。

你想循环,直到n == null。 就目前而言,你正在停止一次。

试试这个

 public int count() { int count = 0; for (ListNode n = head; n != null; n = n.next) { count++; } return count; } 

那是因为你从0开始计数,忽略了第一个节点。

而是初始化count=1 ;

 public int count() { int count = 0; for (ListNode n = head; n != null; n = n.next) { count++; } return count; } 

您没有计算最后一个节点。 当你到达要计数的最后一个元素时,n.next将为null,因此count永远不会递增。 您可能会尝试循环,如下所示:

 ListNode n = head; for (ListNode n = head; n != null; n = n.next) { count++; } 

n.next != null是你的问题。 将其更改为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 (ie; the last node will not be counted.) 

你应该先检查null。 如果不是0,则在循环之前设置’counter = 1’。

 if (_first == null) return 0; int count = 1; for (ListNode n = _first; n.Next != null; n = n.Next) { count++; } return count;