【发布时间】:2014-11-16 03:25:48
【问题描述】:
我有一个 Java 类,它由一个节点列表 WordNode 组成,它具有类 Word 的属性和一个名为 next 的 WordNode 对象,用作对下一个节点的引用,如下所示:
class WordNode
{
Word word;
WordNode next;
WordNode(Word w)
{
word = w;
next = null;
}
Word getWord()
{
return word;
}
}
而Word 类有一个名为name 的字符串:
class Word
{
String name;
Word(String n)
{
this.name = n;
}
public String getName()
{
return name;
}
public void setName(String n)
{
name = n;
}
}
我有一个类,它是一个自定义的 LinkedList,我必须通过指定单词名称来添加和删除单词。我可以毫无问题地添加,但是当我想删除时,我遇到了一些问题。删除方法如下:
boolean remove(Word w)
{
WordNode wm = new WordNode(w);
if (list == null) return false; //can't delete on an empty list
else
{
WordNode aux = list;
while(aux != null)
{
if (wm.word.getName().compareTo(aux.word.getName()) == 0 ) //if the word to delete is found
{
if (aux.next == null) //to erase the last element
{
aux = null;
}
else
{
aux.word.setName(aux.next.word.getName()); //set current node's name to equal next node's
WordNode temp = aux.next.next;
aux.next = null; //to erase current node
aux.next = temp; //re-refer
}
return true;
}
else aux = aux.next;
}
return false; //reachable if word is not found
}
}
list 应该是包含所有节点的 LinkedList。 aux 是一个辅助列表,它将循环通过 list 以避免取消链接。所以,如果我选择删除一个 WordNode,我会比较名称。节点在任意位置,除了最后一个节点:
if (aux.next == null) //to erase the last element
{
aux = null;
}
我希望使该节点为空以标记列表的新结尾,但它不会被删除。我可以改变什么来删除最后一个元素?感谢您提前提供任何帮助/建议
【问题讨论】:
-
aux = null 只是将您对对象 aux 的引用设置为 null。最好的方法就是 aux.prev.next = null
-
我没有“prev”字段。但这不就是和
aux = null一样吗? -
if (aux.next == null)只是告诉您您的辅助是列表中的最后一个节点。将最后一个元素的引用设置为 null 不会影响前一个节点,因为它的下一个节点直到引用您认为已删除的元素。这就是为什么你需要跟踪你之前的节点。
标签: java linked-list