search function for doubly linked list

1.4k views Asked by At

I have following doubly linked list search function

def search (self, element):
    current=self.head
    index=1
    if current == None:
        return -1
    else:
        while current.data !=element:
            current=current.next_node
            index=index+1
        if current != None:
            return index
        else:
            return -1

I want it to return -1 when no element can be found. However, it does not work as I expected. Could anyone tell me why?

1

There are 1 answers

1
Pynchia On BEST ANSWER

This should work (I haven't checked):

def search (self, element):
    current=self.head
    index=1
    while current != None:
        if current.data == element:
            return index
        current = current.next_node
        index += 1
    return -1

Still based on the assumption that index starts from one, if that is what you prefer. Normally offets/indexes are much more useful when they start from zero (as they do in python by default in all built-in functions/operators).