3 回答

TA貢獻1877條經(jīng)驗 獲得超1個贊
問題出現(xiàn)在您的第一個循環(huán)中:
while cur_node1.next is not None or cur_node2.next is not None:
這意味著兩個節(jié)點之一可以具有next屬性None。如果該節(jié)點的數(shù)據(jù)也小于另一個節(jié)點中的數(shù)據(jù),則該節(jié)點變量將設置為None。然后while再次評估條件,并產(chǎn)生錯誤,因為該None值沒有next屬性......
cur_nodeX.next通過檢查屬性而None不是其本身,實際上使算法變得過于復雜cur_nodeX。因此,在第一個循環(huán)完成后,您仍然需要從兩個列表中添加節(jié)點。此外,您的代碼假設兩個列表都不為空。
while因此,根據(jù)當前節(jié)點而不是它們的屬性來設置條件next:
def merge(l1, l2):
cur_node1 = l1.head
cur_node2 = l2.head
l3 = LinkedList()
while cur_node1 is not None or cur_node2 is not None:
if cur_node1 is None or cur_node2 is not None and cur_node1.data > cur_node2.data:
l3.append(cur_node2.data)
cur_node2 = cur_node2.next
else:
l3.append(cur_node1.data)
cur_node1 = cur_node1.next
return l3

TA貢獻1827條經(jīng)驗 獲得超9個贊
對于任何想知道的人來說,這都是有效的。
def merge(l1, l2):
cur_node1 = l1.head
cur_node2 = l2.head
l3 = LinkedList()
while True:
if cur_node1 is None:
while cur_node2.next is not None:
l3.append(cur_node2.data)
cur_node2 = cur_node2.next
l3.append(cur_node2.data)
break
elif cur_node2 is None:
while cur_node1.next is not None:
l3.append(cur_node1.data)
cur_node1 = cur_node1.next
l3.append(cur_node1.data)
break
if cur_node1.data > cur_node2.data:
l3.append(cur_node2.data)
cur_node2 = cur_node2.next
elif cur_node1.data < cur_node2.data:
l3.append(cur_node1.data)
cur_node1 = cur_node1.next
return l3

TA貢獻1784條經(jīng)驗 獲得超8個贊
打印“1 -> 2 -> 12 -> 45 -> 69 -> 70 -> 99 -> 100”
def merge(l1, l2):
cur_node1 = l1.head
cur_node2 = l2.head
l3 = LinkedList()
while cur_node1 and (cur_node1.next is not None or cur_node2.next is not None):
if cur_node1.data > cur_node2.data:
l3.append(cur_node2.data)
cur_node2 = cur_node2.next
else:
l3.append(cur_node1.data)
cur_node1 = cur_node1.next
if cur_node1.next is None:
l3.append(cur_node1.data)
while cur_node2.next is not None:
l3.append(cur_node2.data)
cur_node2 = cur_node2.next
l3.append(cur_node2.data)
elif cur_node2.next is not None:
l3.append(cur_node2.data)
while cur_node1.next is not None:
l3.append(cur_node1.data)
cur_node1 = cur_node1.next
l3.append(cur_node1.data)
return l3
添加回答
舉報