你好,所以我无法完成我的任务,因为我很难弄清楚如何在我的链表中设置搜索方法。现在我仍然想学习如何配置链表,我不能完成任何一个其他方法,如删除,或替换,如果我不能找出搜索方法。出于某种原因,我的结果一直是空的。这就是我到目前为止所拥有的......
public class WordList {
private WordMeaningNode list;
WordList()
{
list = null;
}
void add(WordMeaning b)
{
WordMeaningNode temp = new WordMeaningNode(b);
try
{
temp.Next = list;
list = temp;
}
catch(NullPointerException e)
{
System.out.println("Null Pointer Exception");
}
}
public String toString()
{
String result="";
WordMeaningNode current = list;
while (current != null)
{
result += current.Words.word + " - " + current.Words.meaning + "\n";
current = current.Next;
}
return result;
}
public WordMeaning findword (WordMeaning Word)
{
WordMeaningNode Checker = new WordMeaningNode(Word);
boolean found = false;
if (list.isEmpty() == true)
{
return null;
}
else
{
while(list.Next != null && !found)
{
if(list.Words.word.compareTo(Checker.Words.word)== 0)
{
found = true;
}
else
{
list = list.Next;
found = false;
}
}
}
if(found == true)
{
return list.Words;
}
else
{
return null;
}
}
答案 0 :(得分:2)
您的版本实际上会在每次破坏列表的迭代中更改list
(实际上是列表的根(或第一个)节点)。您的查询方法不应更改列表本身。只需在while循环中使用临时(本地)节点变量(我的名为current
),如下所示:
public WordMeaning findWord (WordMeaning word)
{
if (list.isEmpty())
{
return null;
}
boolean found = false;
WordMeaningNode current = list;
while(current != null)
{
if(current.Words.word.compareTo(word)== 0)
{
found = true;
break;
}
current = current.Next;
}
return current;
}
答案 1 :(得分:1)
这是如何在链表中查找元素的示例:
public class LinkedList<T> {
private LinkedList<T> next;
private T data;
public LinkedList(T value) {
data = value;
}
public LinkedList<T> next() {
return next;
}
public T value() {
return data;
}
public void setNext(LinkedList<T> element) {
next = element;
}
public void setValue(T value) {
data = value;
}
}
public LinkedList<Integer> find(LinkedList<Integer> head, int data) {
LinkedList<Integer> elem = head;
while (elem != null && elem.value() != data) {
elem = elem.next();
}
return elem;
}