Python - LinkedList 混乱

问题描述 投票:0回答:1
class Node:
    def __init__(self, data=None, next=None):
        self.data = data
        self.next = next

class LinkedList:
    def __init__(self):
        self.head = None    

    def insert_at_end(self,data):   >>> this function is working
        print('self.head: ', self.head)
        if self.head is None:
            self.head = Node(data, None)
            return
        
        itr = self.head

        while itr.next != None:
            itr = itr.next

        itr.next = Node(data, None)
def insert_at_end(self,data):   >>> this function is NOT working
    n = self.head
    node = Node(data, None)
    if n is None:
        n = node
        return
    
    while n.next != None:
        n = n.next
    n.next = node

当我在末尾添加一个节点时,不工作的函数给我一个空列表,但正在工作的函数给我一个列表。我认为我错过了一个基本点,但无法理解。我是 Python 新手,正在学习 DSA。

if __name__ == '__main__':
    ll = LinkedList()
    ll.insert_at_end(100)
    ll.insert_at_end(101)
    ll.print_ll()

工作函数给了我 100-->101--> 不起作用的函数给了我空链表。

下面是我在两种情况下使用的打印功能。

    def print_ll(self):
        if self.head == None:
            print("Empty Linked List")
            return

        n = self.head
        strll = ''
        
        while n != None:
            strll += str(n.data) + '-->'
            print("linkedlist: ", strll)

            n = n.next
python singly-linked-list
1个回答
0
投票

您遇到的问题是:

n = self.head
n = node

与以下内容不同:

self.head = node

第一个版本只是将两个不同的值分配给同一个局部变量

n
,而第二个版本以将在函数外部持续存在的方式修改
head
self
属性。

© www.soinside.com 2019 - 2024. All rights reserved.