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

标签 java recursion linked-list

我的任务是编写一个包装器和递归方法来搜索给定的项目并返回该项目在链表中的索引。这是我的代码,它适用于列表中的项目,但是当给定一个不在列表中的项目时,它只返回尾部的索引。知道我在这里做错了什么吗?

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

关于java - 在java中的递归链表中搜索项目的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53272407/

相关文章:

c++ - 如何在boost spirit中设置最大递归

java - 删除循环链表的尾部元素

Java JDBC 与 Eclipse 的连接

java - 为我的 Java 棋盘游戏优化我的 "capture"算法

Java 编码标准 : variable declaration

c - 链表 C : add node to beginning, 意外的 '0' 值

java : remove words from ArrayList<String>

java - Android应用程式在手机启动时持续当机

java - 我该如何解决这个递归二叉树问题?

计算一个节点是否在 BST 中有任何子节点