문제

For my java program, i'm using a SingleLinkedList. The following is my code for indexOf which I tested and it worked. My question is how I can change my indexOf to lastIndexOf. I'm kind of confused on how it works and how to do it.

/**
 * Returns the index of the first occurrence of the specified element in this list, or -1 if this list
 * does not contain the element. More formally, returns the lowest index i such that 
 * (o==null ? get(i)==null : o.equals(get(i))), or -1 if there is no such index.
 * @param item
 * @return the index of the first occurrence of the specified element in this list, 
 * or -1 if this list does not contain the element
 */
public int indexOf(E item) {

    Node<E> temp = head;
    for(int i=0; i < size; i++){
        if(temp.data.equals(item))
            return i;
        temp = temp.next;
    }
    return -1;

}

Here is the java doc and header for lastIndexOf:

/**
 * Returns the index of the last occurrence of the specified element in this list,
 * or -1 if this list does not contain the element. More formally, returns the highest
 * index i such that (o==null ? get(i)==null : o.equals(get(i))), or -1 if there is no such index.
 * @param item
 * @return the index of the last occurrence of the specified element in this list, 
 * or -1 if this list does not contain the element
 */
public int lastIndexOf(E item) {
    // TODO Auto-generated method stub
    return 0;
}
도움이 되었습니까?

해결책

Just use a variable to store the biggest index found, and return that:

/**
 * Returns the index of the last occurrence of the specified element in this list,
 * or -1 if this list does not contain the element. More formally, returns the highest
 * index i such that (o==null ? get(i)==null : o.equals(get(i))), or -1 if there is no such index.
 * @param item
 * @return the index of the last occurrence of the specified element in this list, 
 * or -1 if this list does not contain the element
 */
public int lastIndexOf(E item) {
    int index = -1;
    Node<E> temp = head;
    for(int i=0; i < size; i++){
        if(temp.data.equals(item))
            index = i;
        temp = temp.next;
    }
    return index;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top