Katie2423
Katie2423

Reputation: 121

Python LinkedList Search

I'm writing code for a Linked List in Python and here's part of the code:

class LinkedList:
    def __init__(self):
        self.head = None

    def search(self, n, value):
        if n is None:
            return False
        elif n.data == value:
            return True
        else:
            return search(n.next, value)

    def append(self, new_value):
        if self.head is None:
            self.head = LinkedListNode(new_value)
        else:
            node = self.head
            while node.next != None:
                node = node.next
            node.next = LinkedListNode(new_value)

    def remove(self, position):
        if position > 0:
            node = self.head
            l = 0
            while node != position - 1:
                l += 1
                node = node.next
            node.next = node.next.next
        elif position == 0:
            self.head = self.head.next

I'm just wondering how to implement the search() method? I think I have the right idea, but it's not working. Thank you!

Upvotes: 3

Views: 74

Answers (1)

falsetru
falsetru

Reputation: 369054

When you call the method inside the same class, you need to qualify it with self.

def search(self, n, value):
    if n is None:
        return False
    elif n.data == value:
        return True
    else:
        return self.search(n.next, value)  # <--

BTW, current search implementation requires user to pass n (LinkedList.head maybe). So I would make a wrapper to search from head, so user doesn't need to specify linked_list_instance.head every time:

def search_from_head(self, value):
    return self.search(self.head, value)

Upvotes: 3

Related Questions