I just started a data structures and algorithms class and was introduced to linked lists for the first time.
I have a decent understanding of how they work in theory but am having a hard time working with them.
I am struggling with this homework assignment:
Write a method lastIndexOf that accepts an integer value as a parameter and that returns the index in the list of the last occurrence of that value, or -1 if the value is not found in the list. For example, if a variable list stores the following sequence of values, then the call of list.lastIndexOf(18) should return 6 because that is the index of the last occurrence of 18:
[1, 18, 2, 7, 18, 39, 18, 40]
If the call had instead been list.lastIndexOf(3), the method would return -1 because 3 does not appear in the list. You may not call any other methods of the class to solve this problem.
Assume that you are adding this method to the LinkedIntList class as defined below:
public class LinkedIntList {
private ListNode front; // null for an empty list
...
}
Here is my code:
public int lastIndexOf(int value) {
ListNode current = front;
int target;
while (current != null) {
if(current.data == value) {
target = current.data;
return target;
}
current = current.next;
}
return -1;
}
Now the 2 issues I am facing are 1) that I am returning the actual value of the node and not its index, and 2) that I am only returning the first occurrence of that value and not the last.
I hope this isn’t a stupid question and I appreciate your help.
>Solution :
Set target to -1 and return target after the loop; if the value is found update target to the current index. Obviously, target will thus be the last match after the loop (or -1 if there were no matches). You could use a for loop and i to keep the index. Something like,
public int lastIndexOf(int value) {
ListNode current = front;
int target = -1;
for (int i = 0; current != null; i++) {
if (current.data == value) {
target = i;
}
current = current.next;
}
return target;
}