簡體   English   中英

鏈表如何到第二個節點

[英]how does the linked list goes to the second node

所以我在python中學習鏈表,但我不明白鏈表如何進入第二個節點,因為它將下一個節點指定為根節點,請向我解釋,謝謝。 編碼

class Node
    def __init__(self,d,n=None,p=None):
        self.data=d
        self.next_node=n
        self.previous_node=p
    def __str__(self):
        return ('(' + str(self.data) + ')')

class linked_list:
    def __init__(self,r=None):
        self.root=r
        self.size=0
    def add(self,d):
        new_node=Node(d,self.root)#here i didn't understand how we assign the next node
        self.root=new_node
        self.size +=1
        
    def find(self,d):
        this_node=self.root
        while this_node is not None:
            if this_node.data==d:
                print(this_node.next_node)
                return this_node.data
            else:
                this_node = this_node.next_node
        return None
    def remove(self,d):
        this_node=self.root
        previouse_node=None
        while this_node is not None:
            if this_node.data==d:
                if previouse_node is not None:
                    previouse_node.next_node=this_node.next_node
                else:
                    self.root=this_node.next_node
                    self.size -=1
            else:
                previouse_node=this_node
                this_node=this_node.next_node
        return False
    def print_list(self):
        this_node = self.root
        while this_node is not None:
            print(this_node, end='->')
            this_node = this_node.next_node
        print('None')
l_list=linked_list()
l_list.add('4')
l_list.add('40')
l_list.add('5')
l_list.print_list()

#///////////////////////////////////////////////// /////////////////////////////////////

在 add 函數中,我們創建了一個新節點,它將成為我們的新根,也就是我們的新第一個元素。 因此,我們首先將當前根分配為新節點的 next_node。 之后,我們將新節點設為新的根節點。

linked_list.root屬性實際上就像一條尾巴。 當添加一個新節點時,它成為原始rootnext_node並且root被分配給新節點(使其內容成為尾,而不是根)。

此外,Node 類建議使用雙向鏈表,但它的previous_node值沒有由 links_list.add 正確分配。

如果這不是您的代碼,那么它就不是一個值得學習的好例子。 如果是,那么它需要更多的工作,您可能應該在紙上畫出將節點添加到列表中應該產生的鏈接。

例如:

linked_list.root
               |
               v
    None <-- node1 --> None

linked_list.add(node2) ...

應該發生什么:

linked_list.root
               |
               v
    None <-- node1 --+
               ^     |
               |     v 
               +--- node2 --> None
              

實際發生的情況:

    linked_list.root        # points to the last node added (i.e. tail)
                   |
                   v
        None <-- node2 --> None  # missing link to node1
                   ^       
                   |        
  None <-- node1 --+ 
              

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM