2

Basically, i want to check if an item is in a Linked List. The function is described as __contains__ where if I type 3 in myList, it would either return True or False depending whether there is an integer 3 in the Linked List.

class Node:
    def __init__(self,item = None, link = None):
        self.item = item
        self.next = link

    def __str__(self):
        return str(self.item)

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

    def __str__(self):
        current = self.head
        ans = str(current)
        for _ in range(len(self)):
            current = current.next
            ans += '\n'
            ans += str(current)
        return ans

    def _get_node(self,index):
        if 0<= index< len(self):
            current = self.head
            while index>0:
               current = current.next
               index -=1
            return current

    def __contains__(self,item):         #need some help here
        if self.isEmpty():
            raise StopIteration("List is empty")
        if self.head == item:
             return True
        nextItem = self.head.next

    def insert(self,index,item):
        if index < 0 or index > len(self):
            raise IndexError("Index is out of range")
        else:
            newNode = Node(item)
            if index == 0:
                newNode.next = self.head
                self.head = newNode
            else:
                before = self._get_node(index-1)
                newNode.next = before.next
                before.next = newNode
            self.count+=1
            return True

if __name__ == "__main__":
    L = LinkedList()
    L.insert(0, 0)
    L.insert(1, 1)
    L.insert(2, 2)
    L.insert(3, 3)
    print(0 in L)

I'm quite confused when it comes to iterating over a linked list and to check if an item is in it. The print(0 in L) in the last line should return True since 0 is indeed in the Linked List.

Maxxx
  • 3,688
  • 6
  • 28
  • 55
  • 2
    I would suggest first making `LinkedList` instances iterable. See [**_How to make a custom object iterable?_**](https://stackoverflow.com/questions/21665485/how-to-make-a-custom-object-iterable), Then writing `__contains__()` will be relatively easy—just iterate through the `Node`s until you either find the item or reach the end of the list without finding it. – martineau Sep 16 '17 at 01:36
  • please paste the code of the _get_node() function – GuangshengZuo Sep 16 '17 at 01:39
  • @GuangshengZuo please see the updated question – Maxxx Sep 16 '17 at 01:49

1 Answers1

1

Here is the answer for your issue:

def __contains__(head,data):
    if head == None:
        return False
    else:
        p = head
        while p is not None:
            if p.data == data:
                return True
            p = p.next
        return False