I'm currently a freshman comp sci student working on learning data structures both through my class and also online.
I'm new to stack too but it has helped me a lot in the past.
My current problem is searching through a LinkedList to return the last index of which the number appears in the list.
I feel like this has to do somewhat with recursion and continually searching until you can somehow check for sure that that is the last occurrence of that item, then return its index.
However my first semester Java course did not cover recursion at all and I'm sort of at a loss.
Being in these courses I'm not asking for the flat out answer, I just need some direction. Or reassure me that I'm on the right path with looking into recursion at all?
Also, here is what I have attempted so far. Thanks for the help!
public int getLastIndexOf(int lastItem) { //goal is to return the lastindex at which that number appears last
Node current;
current = head;
int count = 0; //count variable
while (current.next != null) { //go through list
if (current.dataItem == lastItem) {
//check rest of the list for if that number exists beyond
}
count++; //increment count for every time loop executes
current = current.next; //moves onto next node to check
}
return -1;
}
Consider the list to be a node followed by another list, called the tail. This is pseudocode, note you need two methods, the private
one takes a node, this is the sub list.
public int getLastIndexOf(value) {
return getLastIndexOf(head, value);
}
private int getLastIndexOf(sublist, value) {
//check the tail first (because we want last index)
if (sublist.tail != null) {//list has a tail
int lastIndexInTail = getLastIndexOf(sublist.tail, value); //recursion
if(lastIndexInTail != -1)
return lastIndexInTail + 1; //it's in the sub list, the sub list starts at idx 1
}
// it's not in the tail, check this head
if (sublist.data == value){
return 0; //it's at the front of this list
}
return -1; //it's not in the head or in the tail of sublist
}