Skip to main content
 首页 » 编程设计

Python链表查询

2024年10月17日8exmyth

这是我遇到问题的代码:

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 

代码本身运行良好,但我无法理解插入函数。最初,

Head == None 

所以用参数数据创建了一个新节点,从现在开始这将是新的头部。因此,如果我尝试向该列表中添加一个新节点,则会触发 else 并且新节点:

current.next  

已创建。到目前为止,一切都很好。现在,如果我想添加另一个节点,else 条件将再次触发,但正在创建一个新的当前对象,这不会覆盖旧当前的内存,从而覆盖 current.next 吗?程序怎么会有之前节点的内存呢??

比起你。

请您参考如下方法:

Current 是一个局部变量,指向 一个 Node 对象。覆盖 current 不会破坏节点,它只是使 current 指向其他东西。只要您引用了 current 过去指向的内容,就可以了。在这种情况下,因为您控制着头部,所以您始终能够按自己的方式浏览列表。