python - 如何检查项目是否在链接列表中?

标签 python class linked-list

基本上,我想检查一个项目是否在链表中。该函数被描述为 __contains__,如果我在 myList 中键入 3,它将返回 TrueFalse,具体取决于链表中是否存在整数3。

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)

在遍历链表并检查其中是否有项目时,我感到很困惑。最后一行的 print(0 in L) 应该返回 True,因为 0 确实在链表中。

最佳答案

这是您问题的答案:

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

关于python - 如何检查项目是否在链接列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46249213/

相关文章:

python - 如何合并pandas中的多列值?

python - 通过 pip 安装 SQLAlchemy 时出现 UnicodeDecodeError

c# - IEquatable是否级联?

c++ - 如何为成员使用非默认构造函数?

c - 如何创建链表(指向结构的指针)-c

python - 如何从 scikit-learn 中的混淆矩阵返回误报数组?

python - 对于给定条件,获取 2D 张量 A 中的值的索引,使用这些索引来索引 3D 张量 B

ios - 为什么克隆变量仍然影响原始对象? swift

创建列表

C 当链表为空时删除链表的节点