[英]Linked List Python
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def __len__(self):
cur = self.head
count = 0
while cur is not None:
count += 1
cur = cur.next
return count
def append(self, item):
cur = self.head
while cur is not None:
cur = cur.next
cur.next = ?
我正在嘗試附加到鏈表中,但是我不能使用“ cur.next”,因為cur沒有屬性“ next”。 有什么提示嗎?
謝謝!
我的測試用例:
def test_append_empty() -> None:
lst = LinkedList()
lst.append(1)
assert lst.head.data == 1
def test_append_one() -> None:
lst = LinkedList()
lst.head = Node(1)
lst.append(2)
assert lst.head.next.data == 2
您必須查找self.head
為None
的情況,因為Nonetype接下來將沒有屬性。 還進行迭代,直到在節點中找到下一個指針為“無”為止。 所以應該是cur.next is not None
而不是cur is None
,它在查找Node是否為None。 從邏輯上講,您不能將任何內容附加到“ None
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def __len__(self):
if not self.head:
return 0
cur = self.head
count = 0
while cur is not None:
count += 1
cur = cur.next
return count
def append(self, item):
if not self.head:
self.head=Node(item)
return
cur = self.head
while cur.next is not None:
cur = cur.next
cur.next = Node(item)
測試用例1
l=LinkedList()
l.append(1)
l.__len__() #prints 1
測試用例2
l=LinkedList()
l.append(2)
l.append(3)
l.__len__() #2
temp=l.head
while(temp):
print(temp.data)
temp=temp.next
還包括OP的測試用例
def test_append_empty():
lst = LinkedList()
lst.append(1)
print(lst.head.data == 1)
def test_append_one():
lst = LinkedList()
lst.head = Node(1)
lst.append(2)
print(lst.head.next.data == 2)
test_append_empty() #True
test_append_one() #True
我希望通過mad_的清晰示例,您已經了解了仍然需要處理節點這一概念的想法。
鏈接列表不僅是值列表,而且還是鏈接列表。
由於您似乎有興趣在一門課中進行此操作,因此可以快速實現:
class LinkedList:
def __init__(self, item=None):
self.next = None
self.val = item
def __len__(self):
cur = self
count = 1 if self.val is not None else 0
while cur.next is not None:
count += 1
cur = cur.next
return count
def append(self, item):
if not self.val:
self.val = item
return
cur = self
while cur.next is not None:
cur = cur.next
cur.next = LinkedList(item)
編輯:
由於您已將mad_的len ()成員包括到您的問題中,因此我還添加了一個適合該類的成員。
這里是一些用法示例:
myList = LinkedList()
myList.append('a')
myList.append('b')
myList.append('c')
myList.append('d')
print(len(myList))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.