Python链表实现和对象建模

我正在尝试在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,这也不起作用。

我知道我在这里缺少什么。你能帮我理解吗?

谢谢。

yiqwer 回答:Python链表实现和对象建模

self.tail仅在存在单个节点时设置为self.head。尾部始终更改为指向LAST节点,只有在添加第二个节点之前,该节点才与头节点相同。

每次调用append时,尾部都会更改为指向刚添加的节点。

附加到第一个节点没有太大意义,不是吗?那将摆脱列表的其余部分。

让我们逐行介绍:

def append(self,data):
        self.tail.next = Node(data)

在执行此操作之前,self.tail.nextNone,表示列表到此为止。现在我们将其设置为新节点,该新节点的“下一个”值为“无”。

         self.tail = self.tail.next

由于self.tail需要指向列表中的LAST项目,因此我们需要对其进行更改。因此,以上一行将其更改为指向NEW的最后一项。

         self.length += 1
         return self

这些只是跟踪长度和返回。只要正确完成操作,您就无需遍历列表即可知道其中有多少个节点。

,

如果引用类Node,则它有两个对象:value和next Node。

在“链表”实现中,它的实现方式是也存储尾节点信息。在append函数中,self.tail.next = Node(data)基本上在尾节点之后添加一个新节点,self.tail = self.tail.next将链接列表的尾节点重新分配给新创建的Node(现在是列表的最后一个节点)

例如,让我们采用以下代码:

linkin = LinkedList1(10)
linkin.append(20)
linkin.append(30)
linkin.append(40)
linkin.show_list()
  1. 使用self.head-> Node(10)和self.tail-> Node(10)创建链接列表
  2. 追加20会更改列表:self.head-> Node(10),self.tail.next-> Node(20)[与self.head.next相同] 10-> 20其中10是head和20是尾巴
  3. 追加30将更改列表:self.tail.next-> Node(30)[self.tail在这里是Node(20)],现在将Node(30)制成尾巴10-> 20-> 30其中10是头,尾是30

希望这会有所帮助。

本文链接:https://www.f2er.com/3152665.html

大家都在问