Seriad
Seriad

Reputation: 43

Can't solve indexOf function for Doubly Linked list

I have a function that I can't seem to figure out.

Instructions:

Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element index is 0-based (i.e., the first 'real' node (after dummy header) is index 0). @param x the element to search for

So, what's happening here is the function is passed in an Object, in my case a number. IndexOf is supposed to go through the list of numbers and see if any match. If it finds a match, it will return the INDEX of the object. My issue is that it just returns whatever result is initialized to. How can I make it so it returns the index?

public int indexOf(Object x)
{
    Node current = head; 
    int result = 0;
    for(int i = 0; i < elementCount; i++){
        if(x.equals(current.data)){
          result = i;
          return result;
        }
    }
    return result;
}

Upvotes: 0

Views: 2338

Answers (1)

slider
slider

Reputation: 12990

Your 'current' always points to the head, so even though you're running the for loop for all the elements in the list, you are at every stage comparing 'x' with whatever is in the head.

So, in your for loop, after your test, you should increment 'current'.

for(int i = 0; i < elementCount; i++){
    if(x.equals(current.data)){
         result = i;
         return result;
    }
    current = current.next; // increment current pointer so that it 
                            // points to the next node in the list
}

Also, ideally, you should not initialize result to 0, but to -1. So if x in not found at all, your method will return -1 (instead of 0, which is deceiving).

Upvotes: 1

Related Questions