【问题标题】:Searching for the index of an item in a recursive linked list in java在java中的递归链表中搜索项目的索引
【发布时间】:2018-11-13 01:19:52
【问题描述】:

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

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



}

【问题讨论】:

  • 如果它不在列表中,您希望它返回什么?原因:1 + searchIndex 您正在添加 1,直到您在元素不存在时迭代整个列表。

标签: java recursion linked-list


【解决方案1】:

你的条件是错误的。让我们分解:

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

【讨论】:

    【解决方案2】:

    当您返回 -1 时,您的递归语句会将其加一,并使其与尾节点是否因匹配而返回零无法区分。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-14
      • 2011-08-11
      • 1970-01-01
      • 2017-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多