[英]How to return the middle node of a linked list
在檢查鏈表的中間節點時,我對鏈接列表中的while循環條件如何工作感到困惑
這是我找到鏈表的中間節點的正確代碼
class Node(object):
def __init__(self, data):
self.data = data
self.next = None
class linkedList(object):
def __init__(self):
self.head = None
def append(self, data):
node = Node(data)
if self.head == None:
self.head = node
temp = self.head
while temp.next:
temp = temp.next
temp.next = node
def middle(self):
first = self.head
second = self.head
while second and second.next:
second = second.next.next
first = first.next
print(first.data)
如果我將while循環更改為
while second:
要么
while second.next:
我收到一條錯誤說
AttributeError: 'NoneType' object has no attribute 'next' on line 24
我只是想知道為什么同時擁有second
和second.next
很重要
該解決方案使用兩個指針。 第一個一步采取一步,一次采用第二步。 但是,在采取兩個步驟時,需要驗證兩件事:
如果你跳過一個檢查,它將進入循環但在邊界條件下它找不到下一個。 為了說明:如果有4個節點並且你只在第3個節點檢查second.next
你將有second.next
作為有效,你將進入while
循環但在你內部直接訪問second.next.next
F,S | 1 - > 2 - > 3 - > 4 - >無
對於初學者來說,你的append方法不起作用,並且陷入無限循環中,因為在添加第一個元素時你不會退出追加。 正確的版本是
def append(self, data):
node = Node(data)
if self.head == None:
self.head = node
return
else:
temp = self.head
while temp.next:
temp = temp.next
temp.next = node
至於你的另一個問題,我們想找到偶數和奇數列表的循環中間, second
second.next
覆蓋奇數列表的情況, second
覆蓋偶數列表的情況,因為第二個指針將指向null ,或者它本身就是null,如果你只使用其中一個,你將得到你描述的錯誤,因此你需要在while循環中同時具備這兩個條件
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.