亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

鏈表在 2 個節點后停止,為什么?

鏈表在 2 個節點后停止,為什么?

陪伴而非守候 2022-11-18 14:07:02
第一次發帖在這里。我正在嘗試使用下面的代碼實現鏈表,但不知何故鏈表會在第二個節點之后停止。我期待 9->6->11->8->15->19->7->,但我只得到 9->6->。誰能幫我弄清楚我的代碼有什么問題?謝謝!class Node:    def __init__(self,value):        self.next = None        self.val = value    def __str__(self):        return str(self.val)class SLinkedList:    def __init__(self):        self.head = None        self.tail = None    def append_node(self,value):        if self.head == None:            self.head = self.tail = Node(value)          else:            self.tail.next = Node(value)            self.tail = Node(value)        return selfllist = SLinkedList()llist.append_node(9).append_node(6).append_node(11) \.append_node(8).append_node(15).append_node(19) \.append_node(7)  print(llist.head.next.next) # returned None. Why??
查看完整描述

3 回答

?
慕姐4208626

TA貢獻1852條經驗 獲得超7個贊

self.tail.next = Node(value)    

self.tail = Node(value)

在這里,您將同一個對象放在兩個節點中,這并不是實際需要的。你需要說,現在做self.tail.next尾巴,即self.tail


因此self.tail = Node(value)改為self.tail = self.tail.next


class SLinkedList:

    def __init__(self):

        self.head = None

        self.tail = None

    def append_node(self,value):

        if self.head == None:

            self.head = self.tail = Node(value)

        else:

            self.tail.next = Node(value)

            self.tail = self.tail.next

        return self


查看完整回答
反對 回復 2022-11-18
?
慕斯王

TA貢獻1864條經驗 獲得超2個贊

self.tail = Node(value)如果您替換為,它將起作用self.tail = self.tail.next。您當前的版本設置self.tail.next為具有給定值的新節點,然后設置self.tail為具有相同值的不同節點。它們需要是相同的節點才能使鏈表正常工作。 self.tail.next 是一個等價于的節點Node(value),但Node(value)創建了一個新對象。您需要它們都是同一個對象。如果它們不是同一個對象,則它們self.tail將是一個單獨的對象,而不是鏈表的一部分。



查看完整回答
反對 回復 2022-11-18
?
哆啦的時光機

TA貢獻1779條經驗 獲得超6個贊

當self.head不為空時,append_node()正在創建兩個新節點。它將一個放在next舊尾巴的鏈接中,然后設置self.tail到另一個。結果,self.tail指向一個實際上不在next鏈中的節點。所以當你稍后在它后面添加一個新節點時,它不在列表中。


將新節點分配給一個變量,然后在兩個地方分配它。


    def append_node(self,value):

        new_node = Node(value)

        if self.head == None:

            self.head = self.tail = new_node

        else:

            self.tail.next = new_node

            self.tail = new_node

        return self


查看完整回答
反對 回復 2022-11-18
  • 3 回答
  • 0 關注
  • 153 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號