简体   繁体   中英

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:

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? How can the program have memory of previous Nodes??

Than you.

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

Current is a local variable that points to a Node object. 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. In this case, because you keep a hold of head , you're always able to work your way through the list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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