简体   繁体   English

在java中搜索递归链表中项的索引

[英]Searching for the index of an item in a recursive linked list in java

My task is to write a wrapper and recursive method to search for a given item and return the index of that item within a linked list. 我的任务是编写一个包装器和递归方法来搜索给定的项目并返回链接列表中该项目的索引。 This is the code I have, and it works for items that are in the list, but when given an item that is not in the list it just returns the index of the tail. 这是我的代码,它适用于列表中的项目,但是当给定一个不在列表中的项目时,它只返回尾部的索引。 Any idea what i'm doing wrong here? 知道我在这里做错了什么吗?

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);         
    }   



}

Your conditions are wrong. 你的条件错了。 Let's break down: 让我们分解一下:

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);         
    }   
}

For recursion, you have to state proper conditions. 对于递归,您必须说明适当的条件。 And normally your return is result, and arguments variations. 通常你的回报是结果和参数的变化。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM