计算链接列表中的所有节点 [英] Counting all the nodes in a Linked List
本文介绍了计算链接列表中的所有节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的方法
public int count(){
int count = 0;
for(ListNode n = head; n.next!= null; n = n.next){
count ++;
}
return count;
$ / code $ / pre
这里是我的ListNode.java
public class ListNode {
字符串名称; //列表中的名字
ListNode next; //列表中的下一个节点
ListNode prev; //列表中的前一个节点
/ **
*只有一个名字的构造函数。当
*开始一个列表时,这个表单将是最有用的。
* /
public ListNode(String name){
this.name = name;
next = null;
prev = null;
}
/ **
*具有名称和对前一个列表节点的引用的构造函数。当添加到列表的末尾时,这
*表格将是最有用的。
* /
public ListNode(String name,ListNode node){
this.name = name;
next = null;
prev = node;
$ / code $ / pre
解决方案 end节点会失败 n.next!= null
但它是LinkedList的一部分,所以你应该考虑这一点。这听起来像只是有一个索引错误。
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;
}
}
解决方案 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.
这篇关于计算链接列表中的所有节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文