Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Hello, please answer the \"Your code here\" portions. The implementation of the

ID: 3809160 • Letter: H

Question

Hello, please answer the "Your code here" portions.

The implementation of the methods contains(E e), get(int index), indexOf(E e), lastIndexOf(E e), and set(int index, E e) for MylinkedList were omitted from the textbook (Listing 24.6, page 916-918). Based on the contains(E e) and indexOf(E e) given below, please implement get(int index), lastIndexOf(E e), and set(int index, E e).

return -1; }

/** Return the element from this list at the specified index */ public E get(int index) {

// Your code here! }

/** Returns the index of the last matching element in this list * Returns -1 if no match. */

public int lastIndexOf(Object o) { // Your code here!

}

/** Return and Replace the element at the specified position in this list * with the specified element. */

public E set(int index, E e) { // Your code here!

}

Explanation / Answer

1. public E get(int index)

The below logic will take care even if we give index as greater than size. In that case there won't any value to return at that index. In that case, below logic will return -1.

public E get(int index) {
   if(index>size)
       return -1;
   int counter=0;
   Node current = head;
   while(counter!=index) {
       current = current.next;
       counter++;
   }
   return current.element;
}

2. public int lastIndexOf(Object o)

Below Logic, lastIndex will be set intially as -1.

In case there is no element in list with given Object then lastIndex will not be set inside if so -1 will get return.

In case there is only one element which matches the object then that index will be returned as lastIndex will get updated inside IF.

In case there are more than one element matching with the object then lastIndex will get update every time it matches with object. So, last matched index will be stored in the lastIndex.

public int lastIndexOf(Object o) {
   int lastIndex = -1;
   for (int i = 0; i < size; i++) {
           if (current.element.equals(o)) {
           lastIndex = i;
       }
           current = current.next;
   }
   return lastIndex;
}

3. public E set(int index, E e)

Below logic, in case index is greater than size then -1 will be return as there is no element at that index in the list.

public E set(int index, E e) {
   if(index>size)
       return -1;
   int counter=0;
   Node current = head;
   while(counter!=index) {
       current = current.next;
       counter++;
   }
   return current.element=e;
}