Java 显示我的LinkedList的元素不起作用
调用remove方法后,我调用display,得到一个空列表;但是,如果我首先调用display方法,它将显示正确的列表,我猜“first”值到达了列表的末尾,或者我在某处得到了一个断开的节点。谢谢你的帮助Java 显示我的LinkedList的元素不起作用,java,list,linked-list,Java,List,Linked List,调用remove方法后,我调用display,得到一个空列表;但是,如果我首先调用display方法,它将显示正确的列表,我猜“first”值到达了列表的末尾,或者我在某处得到了一个断开的节点。谢谢你的帮助 public class LinkedList { private Node first; public LinkedList() { first = null; } //add students to the list
public class LinkedList {
private Node first;
public LinkedList()
{
first = null;
}
//add students to the list
public void add(Student s)
{
Node newNode = new Node(s);
newNode.next = first;
first = newNode;
}
//remove duplicate records (return true if duplicate found)
public boolean remove(String fn, String ln)
{
Student remove;
boolean found = false;
int duplicate = 0;
while(first != null)
{
if(first.value.getFname().equals(fn) && first.value.getLname().equals(ln))
{
duplicate++;
if(duplicate > 1)
{
remove = first.value;
found = true;
}
}
first = first.next;
}
if(found)
return found;
else
return found;
}
//display list of student
public void display()
{
if(first == null)
System.out.println("List is empty!");
else
{
while(first != null)
{
System.out.println(first.value);
first = first.next;
}
}
}
}
主要
输出
run:
true
List is empty!
BUILD SUCCESSFUL (total time: 1 second)
问题出在add()方法中。看看里面。:) 问题出在add()方法中。看看里面。:) 您正在使用链表的头(
first
)作为remove
方法中的迭代器。相反,请使用局部变量:
for (Node current = first; current != null; current = current.next) {
if (current.value.getFname().equals(...
...
...
}
您正在使用链表的头(
first
)作为remove
方法中的迭代器。相反,请使用局部变量:
for (Node current = first; current != null; current = current.next) {
if (current.value.getFname().equals(...
...
...
}
你有一些虫子。你不可能是这个意思: 如果(找到) 发现退货; 其他的 发现退货 这将永远成为现实 设置一个断点,画一幅数据结构图(是的,用铅笔),并在调试程序中观察数据结构,同时浏览代码 如果你在这里得到一个密码答案,你也将无法计算出下一个作业。对不起
-阿奇博尔德教授。你有一些错误。你不可能是这个意思: 如果(找到) 发现退货; 其他的 发现退货 这将永远成为现实 设置一个断点,画一幅数据结构图(是的,用铅笔),并在调试程序中观察数据结构,同时浏览代码 如果你在这里得到一个密码答案,你也将无法计算出下一个作业。对不起
-阿奇博尔德教授。逐步检查您的代码,并注意在第一次调用
删除(…)
后的值会发生什么变化
提示:它将是null
由于LinkedList.first
是LinkedList
对其内容的唯一引用,因此在您调用remove()
之后,列表已经“忘记”了它包含的内容。逐步浏览您的代码,并注意在第一次调用remove(…)
之后first
的值会发生什么变化
提示:它将是null
由于LinkedList.first
是LinkedList
对其内容的唯一引用,在您调用remove()
之后,列表已经“忘记”了它包含的内容。您永远不会删除任何内容……您只需查看列表中是否有内容,然后迭代到其末尾,其中first=null。您可以使用“break”语句中断while循环。另外,您总是返回“find”-因此在结尾不需要if-else。您如何知道first=null。。。我不认为这是正确的解决方案,我确信打破循环是正确的。。如果有多个副本呢?您永远不会删除任何内容…您只需查看列表中是否有内容,然后迭代到其结尾,其中first=null。您可以使用“break”语句中断while循环。另外,您总是返回“find”-因此在结尾不需要if-else。您如何知道first=null。。。我不认为这是正确的解决方案,我确信打破循环是正确的。。如果有多个副本呢?if(found).
事件不会总是返回true。它完全等同于一个简单的返回find
。if(found).
东西并不总是返回true。它完全等同于一个简单的返回find
。是的,但是如果我在使用display方法时使用局部变量,即使用“first”变量,它将打印整个数组。我没有删除任何东西…是的,但是如果我在使用display方法时使用局部变量,它会打印整个数组。我没有删除任何东西…好吧,我这里有两个问题,1我没有删除任何东西,2 b/c我使用一个类变量,当first=first.next到达它的结尾时first=null,因此“dipalay”方法是空的。一种解决方案是使用局部变量并遍历列表,但如何删除链接?这里有两个问题,1我没有删除任何内容,2 b/c我在first=first时使用类变量。next到达其结尾时first=null,因此“dipalay”方法为空。一种解决方案是使用局部变量并遍历列表,但如何删除链接?