简体   繁体   中英

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时,您的递归语句会向其添加一个,并使其与尾节点因匹配而返回零无法区分。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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