我正在学习在Java中实现链表,当我遇到计算链表中节点的示例代码时
class ListNodes { int item; ListNodes next; }
int count(Node ptr_start)
{
int c=0;
Node ptr = new Node();
ptr = ptr_start;
while(ptr != null)
{
c++;
ptr = ptr.next;
}
return c;
}
我在这里几乎没有问题究竟是什么
下一个ListNodes;
和'ListNodes'的名称与它的类相同?
是什么
ptr = ptr_start; 我认为这是指针以一个值开头,但除了'ptr_start'之外还有其他值吗? 和
ptr = ptr.next;
我认为它移动到下一个指针但是'next'将它移动到其他指针,它接下来是'Java定义的还是用户定义的东西? 有点似乎我不明白这个代码是什么,请帮帮忙?
答案 0 :(得分:2)
class ListNodes {
int item;
ListNodes next;
}
int count(Node ptr_start)
{
int c=0;
Node ptr = new Node(); // IT CREATES A NEW NODE NAMED ptr.
ptr = ptr_start; //ptr_start is a node which is coming from the other class name. and ptr is
// has became same as ptr_start (the first node)
while(ptr != null) // this loop will go as long as the ptr != null.
{
c++;
ptr = ptr.next; //ptr = ptr.next means ptr will become the next node in this line.
}
return c;
}
我希望我回答你的一些困惑。另外,请阅读oracle文档以便更好地理解。 :)
答案 1 :(得分:1)
首先,如果您是链接列表的新手,请参阅此链接,它有一个很好的解释:
http://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html
第二个ListNodes next
是listNode中的项目,每个项目都被称为next
。
第三个是ptr = ptr_start;
是指向链表的指针ptr是在linkedList的开头设置的。
ptr = ptr.next;
是增加指针并告诉链表跳转到下一个项目
答案 2 :(得分:1)
ListNodes确实是类的名称,也是它的实例化对象。 “Next”只是引用链中的下一个ListNodes,因此属于ListNodes类型。
顺便说一下,我不喜欢班级名称的复数形式。
ptr被保留作为对ListNodes的引用(再次,aaaaaaargh与复数!)我们正在指向,因为我们正在突破列表。所以我们在这个方法中做的第一件事是将ptr设置为ptr_start,因为ptr_start是列表中的第一个ListNodes,我们想从头开始计数。
然后发生的事情是,只要有新的节点要访问,我们就会一步一步向前移动ptr。