[英]remove() method of a linked list
我正在上一个编程课,我有以下任务。
编写一个菜单驱动的程序,它接受单词及其含义,或以字典顺序显示单词列表(即在字典中)。 当要将条目添加到字典时,必须先将该单词作为一个字符串输入,然后将该含义输入为单独的字符串。 另一个要求 - 不时的话语已经过时了。 发生这种情况时,必须从字典中删除这样的单词。
使用JOptionPane类输入信息。
使用链表的概念来执行此练习。 您至少需要以下课程:
对于输出,程序应该生成两个可滚动列表:
到目前为止,除了删除方法之外,我编写了所有代码,而且我不知道如何编写代码,所以任何人都可以帮助我。 我已经编写了add方法,但现在我不知道从哪里开始使用我的WordList类中的remove方法。 我的课程如下。
WordList类:
public class WordList {
WordMeaningNode list;
WordList() {
list = null;
}
void add(WordMeaning w)// In alphabetical order
{
WordMeaningNode temp = new WordMeaningNode(w);
if (list == null)
list = temp;
else
{
WordMeaningNode aux = list;
WordMeaningNode back = null;
boolean found = false;
while(aux != null && !found)
if( temp.getWordMeaning().getName().compareTo(aux.getWordMeaning().getName()) < 0 )
found = true;
else
{
back = aux;
aux = aux.next;
}
temp.next = aux;
if (back == null)
list = temp;
else
back.next = temp;
}
}
boolean listIsEmpty() {
boolean empty;
if (list == null) {
empty = true;
} else {
empty = false;
}
return empty;
}
public String toString()
{
String result = "";
int count = 0;
WordMeaningNode current = list;
while (current != null)
{
count++;
result += current.getWordMeaning().getName() + "\n" + "\t" + current.getWordMeaning().getDefinition();
current = current.next;
}
return result + "\nThe number of words is : " + count;
}
}
我尝试使用与add方法相同的方法格式,但是没有真正起作用,或者我做错了。
要从LinkedList中删除项目,您应该遍历其节点。 然后,如果发现了occurence,则连接上一个和下一个节点,设置previous.next = next
:
boolean remove(String word) {
if (list == null) // list is empty
return false;
WordMeaningNode n = list;
WordMeaningNode prev = null;
do {
if (n.wordMeaning.name.equals(word)) { // word found
if (prev != null) {
prev.next = n.next; // connect previous to next
} else {
list = list.next; // connect head to next
}
return true;
}
prev = n;
n = n.next;
} while (n != null); // repeat till the end of a list
return false;
}
在主代码中,更改case 2
:
if (diction.remove(word)) {
obsolete.add(new WordMeaning(word, " "));
// notify about deletion
} else {
// notify that word don't exist.
}
因为你真的不需要NullPointerException
。
要从列表中删除元素,您需要在要删除的元素之前找到该元素,并在要删除的元素之后设置其元素的next
引用。
你会有一些(不是相互排斥的)角落案例需要注意:
next
引用设置为null
) 此外,我发现您需要保留已删除项目的列表,因此请不要忘记在此过程中保留对已删除项目的引用,并将其添加到过时单词列表中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.