3 回答

TA貢獻(xiàn)1877條經(jīng)驗(yàn) 獲得超1個(gè)贊
問題出現(xiàn)在您的第一個(gè)循環(huán)中:
while cur_node1.next is not None or cur_node2.next is not None:
這意味著兩個(gè)節(jié)點(diǎn)之一可以具有next屬性None。如果該節(jié)點(diǎn)的數(shù)據(jù)也小于另一個(gè)節(jié)點(diǎn)中的數(shù)據(jù),則該節(jié)點(diǎn)變量將設(shè)置為None。然后while再次評(píng)估條件,并產(chǎn)生錯(cuò)誤,因?yàn)樵揘one值沒有next屬性......
cur_nodeX.next通過檢查屬性而None不是其本身,實(shí)際上使算法變得過于復(fù)雜cur_nodeX。因此,在第一個(gè)循環(huán)完成后,您仍然需要從兩個(gè)列表中添加節(jié)點(diǎn)。此外,您的代碼假設(shè)兩個(gè)列表都不為空。
while因此,根據(jù)當(dāng)前節(jié)點(diǎn)而不是它們的屬性來設(shè)置條件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貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超9個(gè)贊
對(duì)于任何想知道的人來說,這都是有效的。
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貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超8個(gè)贊
打印“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
添加回答
舉報(bào)