【发布时间】:2020-03-02 20:58:56
【问题描述】:
我正在尝试在 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),在我的逻辑中没有循环它应该添加到第一个下一个。
另外,如果我们这样写函数:
def append(self, data):
self.head.next = Node(data)
self.tail = self.head.next
self.length += 1
return self
即使self.tail 引用self.head,这也不起作用。
我知道我在这里遗漏了一些东西。你能帮我理解吗?
谢谢。
【问题讨论】:
标签: python data-structures linked-list