链表indexOf方法实现

LinkedList indexOf method implementation

我的一个程序中有如下方法:

/** 
 * Returns the index of the first occurrence of the specified item.
 * If the specified item in not part of the list
 * the method indexOf returns -1
 * 
 * @param item
 * @return index of the first occurrence of the item; -1 if the word was not found.
 */
public int indexOf(String item) {   

    int index = 0;

    //While we haven't reached the end of the list
    while(head != null) {
        //If the items are equal return true
        if(head.item == item) {
            return index;           
        }
        //Set the head to the next and increment the index  
        head = head.next;
        index++;
    }
    return -1;
}

虽然对我来说一切看起来都是正确的(除了需要将 head.item == item 更改为 head.item.equals(item) 之外),但它没有给我正确的索引。

虽然它确实为不在 lest 中的元素提供了 -1,但每次它返回 0 作为列表中元素的索引时,我终究无法弄清楚为什么指数不递增。

任何输入将不胜感激!谢谢

当您遍历 indexOfcontains 中的列表时,您似乎正在更改 head 值。 head 值应始终指向列表中的第一个条目,并且仅在 appendprepend 需要时才更改。要迭代,您应该使用局部变量来循环遍历列表。此外,您应该使用 .equals 来比较字符串值,而不是 ==.

public int indexOf(String item) {   

    int index = 0;
    Node current = head;

    //While we haven't reached the end of the list
    while(current != null) {
        //If the items are equal return the index
        if(current.item.equals(item)) {
            return index;           
        }
        //Set current to the next and increment the index  
        current = current.next;
        index++;
    }
    return -1;
}