Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to find last index of item in linked list in java

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading