我正在尝试在Python上实现单链表,并且下面的代码可以正常工作,但我不知道如何:
class Node(object):
def __init__(self,data=None,):
self.value = data
self.next = None
class LinkedList1(object):
def __init__(self,data=None):
self.head = Node(data)
self.tail = self.head
self.length = 1
def append(self,data):
self.tail.next = Node(data)
self.tail = self.tail.next
self.length += 1
return self
def show_list(self):
head_copy = self.head
while head_copy is not None:
print(head_copy.value)
head_copy = head_copy.next
测试时:
linkin = LinkedList1(10)
linkin.append(20)
linkin.append(30)
linkin.append(40)
linkin.show_list()
输出:
10
20
30
40
我不明白的是附加功能。我知道self.tail
引用了self.head
,但是sefl.tail.next
是如何将新的Node(data)
添加到最后一个next的,按照我的逻辑,没有循环,它应该添加到first next。 / p>
另外,如果我们以这种方式编写函数:
def append(self,data):
self.head.next = Node(data)
self.tail = self.head.next
self.length += 1
return self
即使self.tail
引用了self.head
,这也不起作用。
我知道我在这里缺少什么。你能帮我理解吗?
谢谢。