【发布时间】:2016-03-08 21:53:26
【问题描述】:
我对递归非常陌生(而且我必须使用它)并且在使用我的一种搜索方法时遇到了一些严重的逻辑问题。请看下面:
//these are methods within a Linked List ADT with StringBuilder functionality
//the goal here is to access the char (the Node data) at a certain index
public char charAt(int index)
{
if((firstNode == null) || (index < 0) || (index >= length + 1))
//firstNode is the 1st Node in the Linked List, where the search begins
{
System.out.println("Invalid Index or FirstNode is null");
IndexOutOfBoundsException e = new IndexOutOfBoundsException();
throw e;
}
else
{
char c = searchForChar(firstNode, index);
return c;
}
}
private char searchForChar(Node nodeOne, int index)
{
int i = 0;
if(nodeOne == null) //basecase --> end
{
i = 0;
System.out.println("nodeOne null, returning null Node data");
return 'n';
}
else if(i == index) //basecase --> found
{
i = 0;
return nodeOne.data; //nodeOne.data holds the char in the Node
}
else if(nodeOne != null) //search continues
{
searchForChar(nodeOne.next, index);
i++;
return nodeOne.data;
}
return nodeOne.data;
}
输出是“nodeOne null,返回 null 节点数据”的长度为 1 的打印。我不明白最后一个 else-if 语句中的递归语句是如何达到的,而第一个 if 语句中的 null 语句似乎也被达到了。
我尝试重新排列 if 语句,使 if(nodeOne != null) 排在第一位,但这给了我一个 NullPointerException。不知道我做错了什么。特别是因为我可以使用toString() 方法打印节点中的数据,所以我知道节点没有空数据。
谁能帮我理解一下?
【问题讨论】:
-
如果您发布了一个完整的示例,我想您将有更好的机会在这里获得有意义的答案/建议 - 例如某人可以运行的程序。我建议您添加一个示例,说明如何调用这些方法以及结果与您的预期有何不同。
-
firstNode从何而来?
-
我做了一些编辑,解释了类、方法和变量的一些用途 - 我希望这会有所帮助。
-
我认为你不应该使用
i并使用return rearchForChar(nodeOne.next, index - 1);并检查index == 0,因为这样你就知道你在正确的节点。 -
@martijnn2008 但不应该索引保持不变,因为这两种方法的重点是在该特定索引处找到一个字符?
标签: java if-statement recursion linked-list nodes