Jim Jim - 1 month ago 10
Java Question

SearchReturn in a Linked List

I'm trying to get my searchReturn function to work but can't seem to get it. Also, It says I have to call my current somewhere else But i'm not sure how else to do it, so I listed it as private Node current; in the beginning of my code. I'm also having issues trying to increment the i so that when it reaches whatever number in my test file it returns that node.

Here's my searchReturn function:

public class List {
private Node head;
private int length;
private Node current;

//Making the LinkedList, with the head as a new Node
//and the size of the list set to 0
public List(){
length = 0;
}

public boolean isEmptyList(){
if (length == 0){
return true;
}
else{
return false;
}
}

//SearchReturn(L, key): returns a pointer to the Node to the index
public Node searchReturn(int key) {
Node current = head;
while(current != null) {
key++;
}
return current;
}

Answer

You need to advance the node to the next one key times:

public Node searchReturn(int key) {
    Node retVal = head;
    int i = 0;
    while(i < key) {
        if (retVal == null) {
            return null;
        }
        retVal = retVal.next();
        i++;
    }
    return retVal;
}