[英]Why my display function of linked list always printing the last element?
My dipslay function of linked list is as follows:- 链表的我的dipslay功能如下: -
public void display()
{
cur = first;
if(isEmpty())
{
System.out.println("no elements in the list");
}
else
{
System.out.println("elements in the list are:");
do {
System.out.println(first.data);
first = first.link;
} while(first.link!=null);
first=cur;
}
where curr
and first
are references of class node 其中
curr
和first
是类节点的引用
public class node
{
int data;
Node link=null;
}
why is this function only printing the last element? 为什么这个函数只打印最后一个元素?
The function looks more or less correct. 该功能看起来或多或少是正确的。 However why are you setting
cur
to first
and then using first
to do the iteration? 但是,为什么要将
cur
设置为first
然后再使用first
来进行迭代? Just use cur
in the iteration so you don't have to reset first
. 只需使用
cur
的迭代,所以你不必重新设置first
。
Check to make sure you're adding nodes into the list correctly. 检查以确保正确地将节点添加到列表中。 So if you think there are 3 elements in the list, run this in
display()
: 因此,如果您认为列表中有3个元素,请在
display()
运行:
System.out.println(first.data);
System.out.println(first.link.data);
System.out.println(first.link.link.data);
This is to check if your links are correct. 这是为了检查您的链接是否正确。
It is not possible to say for sure, but it is probable that your list actually contains only one element; 不可能肯定地说,但您的列表可能实际上只包含一个元素; ie that the code that creates the list is broken.
即创建列表的代码被破坏。
I should also point out that the display
method should use a local variable to step through the elements. 我还应该指出,
display
方法应该使用局部变量来逐步执行元素。 If you use an instance variable (eg first
) you are liable to get different methods interfering with each other. 如果您使用实例变量(例如,
first
),您可能会有不同的方法相互干扰。
Finally, your test for the end of the list is incorrect. 最后,您对列表末尾的测试不正确。 Think carefully about what
first
and first.link
point at when the while
test is executed. 仔细考虑执行
while
测试时first
和first.link
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.