[英]Searching for the index of an item in a recursive linked list in java
我的任务是编写一个包装器和递归方法来搜索给定的项目并返回链接列表中该项目的索引。 这是我的代码,它适用于列表中的项目,但是当给定一个不在列表中的项目时,它只返回尾部的索引。 知道我在这里做错了什么吗?
public int searchIndex(E item) {
return searchIndex(item, head, 0);
}
private int searchIndex(E item, Node<E> node, int index) {
if (node == null) {
return -1;
}
else if (item.equals(node.data)) {
return 0;
}
else {
return 1 + searchIndex(item, node.next, index);
}
}
你的条件错了。 让我们分解一下:
private int searchIndex(E item, Node<E> node, int index) {
if (node == null) {
// ok you say that if list ended found index is -1, i.e. not found
return -1;
}
else if (item.equals(node.data)) {
// item is found, but your result is 0?
// your result should be index
return 0;
}
else {
// your return is an index, so you can't make math on result
// also passing same index over and over again
return 1 + searchIndex(item, node.next, index);
}
}
对于递归,您必须说明适当的条件。 通常你的回报是结果和参数的变化。
private int searchIndex(E item, Node<E> node, int index) {
// break condition: not found at all
if (node == null) return -1;
// break condition: found at index
if (item.equals(node.data)) return index;
// continue condition: proceed to next node and index
return searchIndex(item, node.next, index + 1);
}
当您返回-1时,您的递归语句会向其添加一个,并使其与尾节点因匹配而返回零无法区分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.