1
基本上,我想检查一个项目是否在链接列表中。该函数被描述为__contains__
,其中如果输入3 in myList
,则将返回True
或False
,具体取决于链接列表中是否存在整数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确实在链接列表中。
我建议首先做'LinkedList'实例可迭代。请参阅[** _如何使自定义对象可迭代?_ **](https://stackoverflow.com/questions/21665485/how-to-make-a-custom-object-iterable),然后编写__contains __() ''会比较容易 - 只需遍历'Node's,直到找到该项或到达列表的末尾而没有找到它。 – martineau
请粘贴_get_node()函数的代码 – GuangshengZuo
@广生众请查看更新后的问题 – Maxxx