0
public int lastIndexOf(E e) {
// Left as an exercise
// TODO : Implement this method
Node<E> current = tail;

not sure how to complete this for loop:

for (int i = size - 1; i >= 0; i--) {
    if(e.equals(current))
        return i;
    
} 

return -1;

}

This program is asking me to create a lastIndexOf method for my own LinkedList interface. The lastIndexOf(E e) is supposed to return the index where the element e is found. This is not the same as indexOf(E e) because the algorithm requires me to look from the end of the list rather than the beginning

maj
  • 1
  • 1

1 Answers1

0

The reverse iteration for-loop looks fine. However, you are comparing the wrong thing.

You can get the current element with this.get(index).

public int lastIndexOf(E e) {    
    for (int i = size - 1; i >= 0; i--) {
        E element = get(i);
        if (e == null && element == null) return i;
        if (e != null && e.equals(element)) return i;
    } 
    
    return -1;
}
bvdb
  • 22,839
  • 10
  • 110
  • 123