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時,答案是錯誤的!我不知道有什麼問題鏈接列表的追加方法
請給出一個實際上可以用來重現問題的[mcve]。 – jonrsharpe
這並沒有真正的幫助。請閱讀幫助中心的鏈接頁面。人們應該能夠複製和粘貼問題中的代碼,運行它,然後查看您描述的相同輸出。 – jonrsharpe
您的編輯改進了您的代碼,但它仍然缺少打印「List」的方法。運行該代碼,'print(l)'只是輸出類似於<__ main __。在0x283A148>的列表實例''。 – vyrp