Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 495
Katie2423 Avatar asked Apr 17 '26 11:04

Katie2423


1 Answers

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)
like image 182
falsetru Avatar answered Apr 19 '26 01:04

falsetru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!