Search code examples
javadata-structurescircular-list

Return location of first occurrence and return -1 if not found within the circular linked list


I am trying to assign -1 to the index if is not found within the circular linked list. This is the code I have currently:

public int indexOf(int value){
    Node temp = tail.next;
    int count = 0;
    int index = 0;
    
    while(temp != null) {
        if(temp.value == value) {
            index = count;
            return index;
        }
        count++;
        temp = temp.next;
    }

    return index -1;
    
}

When I test the code these are the results:

The list should be [8 12 14]: [ 8 12 14] *** TESTING INDEXOF *** The index of 8 should be 0: 0 The index of 14 should be 2: 2

The code stops, it is supposed to print the index of 9, which is not in the list, which would be -1. I'm not sure how to fix this. My code just runs and doesn't produce any more results (well not in a time-efficient manner anyway).

Would I have to do :

while(temp == null){ 
index = -1;
break; 
  }

I appreciate any help!


Solution

  • As Kaus in the comments pointed out your while loop will never end in the current state. Assuming that the tail actually points to the last element in your list the following code could be used:

    public int indexOf(int value) {
        Node head = tail.next; //tail should be connected to a head
        Node current = head;
        int index = 0;
        do {
            if (current.value == value) {
                return index;
            }
            current = current.next;
            ++index;
        } while (current != head);
        return -1;
    }
    

    As it goes through all elements (starting from the head) and ends if it encounters head again (assuming that the searching value is not found).