java - How to do lastIndexOf compared to indexOf? -


for java program, i'm using singlelinkedlist. following code indexof tested , worked. question how can change indexof lastindexof. i'm kind of confused on how works , how it.

/**  * returns index of first occurrence of specified element in list, or -1 if list  * not contain element. more formally, returns lowest index such   * (o==null ? get(i)==null : o.equals(get(i))), or -1 if there no such index.  * @param item  * @return index of first occurrence of specified element in list,   * or -1 if list not contain element  */ public int indexof(e item) {      node<e> temp = head;     for(int i=0; < size; i++){         if(temp.data.equals(item))             return i;         temp = temp.next;     }     return -1;  } 

here java doc , header lastindexof:

/**  * returns index of last occurrence of specified element in list,  * or -1 if list not contain element. more formally, returns highest  * index such (o==null ? get(i)==null : o.equals(get(i))), or -1 if there no such index.  * @param item  * @return index of last occurrence of specified element in list,   * or -1 if list not contain element  */ public int lastindexof(e item) {     // todo auto-generated method stub     return 0; } 

just use variable store biggest index found, , return that:

/**  * returns index of last occurrence of specified element in list,  * or -1 if list not contain element. more formally, returns highest  * index such (o==null ? get(i)==null : o.equals(get(i))), or -1 if there no such index.  * @param item  * @return index of last occurrence of specified element in list,   * or -1 if list not contain element  */ public int lastindexof(e item) {     int index = -1;     node<e> temp = head;     for(int i=0; < size; i++){         if(temp.data.equals(item))             index = i;         temp = temp.next;     }     return index; } 

Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -