class _ListNode:
def __init__(self, value, next_):
self._data = value
self._next = next_
return
class List:
def __init__(self):
self._front = None
self._count = 0
return
def _linear_search(self,key):
previous = None
current = self._front
index = 0
while current is not None and key > current._data:
previous = current
current = current._next
index += 1
if current._data != key:
previous = None
current = None
index = -1
return previous, current, index
def __contains__(self, key):
_, _, i = self._linear_search(key)
return i != -1
def append(self, value):
if self._front is None:
self._front = _ListNode(value,None)
else:
self._front._next = _ListNode(value,None)
self._count += 1
l = List()
lst = [1,2,3,4]
i = 0
n = len(lst)
while i < n:
l.append(lst[i])
i += 1
print("{}".format(l.__contains(3))
为了解释更多,我实现了线性搜索方法和contains方法。 contains方法检查数字是否在列表中(返回true或false)。现在,当我需要使用contains方法检查列表中的#3时,答案是错误的!!我不知道这是什么问题
答案 0 :(得分:0)
您的追加方法不会沿着列表向下走。如果self._front._next
已经存在,它只会始终附加到self.front
。这意味着追加循环末尾的内容是你追加的第一件事,你追加的最后一件事就是它们之间没有任何内容。
要更正它,请在列表中查找等待_next
的{{1}}并附加到那里。
None
您还可以定义def append(self, value):
if self._front is None:
self._front = _ListNode(value, None)
else:
n = self._front
while n._next is not None:
n = n._next
n._next = _ListNode(value, None)
self._count += 1
方法来打印_str__
e.g。
List
这不是一个特别有效的实现,因为它构建了一个中间内置def __str__(self):
res = []
n = self._front
while n is not None:
res.append(str(n._data))
n = n._next
return ', '.join(res)
对象。
您的方法中也不需要那些裸list
语句。你可以删除它们。