【发布时间】:2019-03-13 08:36:31
【问题描述】:
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有一个特殊情况。将其分配给self.head如果它是 None -
这不是有效的python代码
-
@MadPhysicist 你在说 OP 吗?
-
@PatrickArtner 哦,我编辑了 OP。对不起!
标签: python python-3.x python-2.7 linked-list singly-linked-list