为什么需要设置尾部值来修改链接Lis中的头部值

2024-04-19 12:20:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要用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


Tags: thehttpsselfcomaddifitemhead
1条回答
网友
1楼 · 发布于 2024-04-19 12:20:36

由于要将新项添加到self.tail指向的列表末尾,因此新项将成为当前尾部(self.tail.NEXT)之后的下一个节点。由于self.tail是指向列表最后一个节点的指针,因此现在必须将其设置为指向新链接的项,因此self.tail=item

相关问题 更多 >