我需要用Python创建一个链表。我已经研究了如何创建我的链表的说明:
https://stackabuse.com/python-linked-lists/
但是我有几个问题关于为什么有些事情是必要的
def add_list_item(self, item):
# add an item at the end of the list
if not isinstance(item, ListNode):
item = ListNode(item)
if self.head is None:
self.head = item
else:
self.tail.next = item
self.tail = item
return
问题是:
我为什么要替换self.tail.next
值,而逻辑上的思考方式是直接更改self.head.next
值(但这不起作用)
为什么更改self.tail.next
也会更改self.head.next
值
为什么需要重置以下值才能使链表正常工作
self.tail = item
由于要将新项添加到self.tail指向的列表末尾,因此新项将成为当前尾部(self.tail.NEXT)之后的下一个节点。由于self.tail是指向列表最后一个节点的指针,因此现在必须将其设置为指向新链接的项,因此self.tail=item
相关问题 更多 >
编程相关推荐