简体   繁体   English

Python 链表查询

[英]Python Linked List Query

Here is the code I am having some issues with:这是我遇到一些问题的代码:

class Node(object):
    def __init__(self, data):
        self.data = data
        self.next = None

class Solution(object):
    def insert(self, head, data):
        if head == None:
            head = Node(data)
        else:
            current = head
            while current.next:
                current = current.next
            current.next = Node(data)
        return head

    def display(self, head):
        current = head
        while current:
            print(current.data)
            current = current.next

The code itself works fine but I'm having trouble understanding the insert function.代码本身运行良好,但我无法理解插入函数。 Initially,最初,

Head == None

So a new Node is made with argument data, this will be the new head from now on.所以一个新的节点是用参数数据创建的,从现在开始这将是新的头。 So if I try to add a new Node to this list, the else is triggered and the new node:因此,如果我尝试向此列表中添加一个新节点,则会触发 else 并且新节点:

current.next 

is created.被建造。 So far so good.到现在为止还挺好。 Now if I wish to add yet another Node, the else condition will trigger again but a new current object is being created, will this not overwrite memory of the old current and thus current.next?现在,如果我想添加另一个节点,else 条件将再次触发,但正在创建一个新的当前对象,这不会覆盖旧当前的内存,从而覆盖 current.next 吗? How can the program have memory of previous Nodes??程序怎么会有之前节点的内存??

Than you.比你。

不,一个新的当前对象没有被创建,而是变量 current 被重新分配,直到它到达列表中的最后一个元素,然后才创建一个新的 Node 对象并将其分配到列表的末尾。

Current is a local variable that points to a Node object. Current 是指向Node 对象的局部变量。 Overwriting current doesn't destroy the Node, it just makes current point to something else.覆盖电流不会破坏节点,它只会使电流指向其他东西。 As long as you have a reference to what current used to point to, you're fine.只要您有对 current 过去指向的引用的参考,就可以了。 In this case, because you keep a hold of head , you're always able to work your way through the list.在这种情况下,因为您保持头脑清醒,所以您总是能够按照自己的方式浏览列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM