輸入兩個單調遞增的鍊錶,輸出兩個鍊錶合成後的鍊錶,當然我們需要合成後的鍊錶滿足單調不減規則。1.遞迴(乙個神奇的方法)
2.非遞迴
def merge(phead1,phead2):
if not phead1:
return phead2
if not phead2:
return phead1
mergedhead = none
if phead1.val <=phead2.val:
mergedhead = phead1
mergedhead.next = merge(phead1.next,phead2)
else:
mergedhead = phead2
mergedhead.next = merge(phead1,phead2.next)
return mergedhead
def merge(phead1,phead2):
p=merge = node(0) #頭結點
while phead1 and phead2:
if phead1.val > phead2.val:
merge.next = phead2
phead2 = phead2.next
else:
merge.next = phead1
phead1 = phead1.next
merge = merge.next
merge.next = phead1 or phead2 #把剩下的鏈結上
return p.next
合併兩個排序鍊錶
struct listnode class solution else while pstart1 null pstart2 null plast next pstart1 plast pend1 pend1 pend1 next pstart1 pend1 else plast next psta...
合併兩個排序鍊錶
描述 將兩個排序鍊錶合併為乙個新的排序鍊錶樣例 給出1 3 8 11 15 null,2 null,返回1 2 3 8 11 15 null。解題思路 將兩個鍊錶當中的對應元素的值進行比較,重新確定新鍊錶當中元素的位置。若第乙個鍊錶當前位置的值小於第二個鍊錶當前值,則不需要改變位置,第乙個鍊錶的指標...
合併兩個排序鍊錶
問題描述 將兩個排序鍊錶合併為乙個新的排序鍊錶 樣例 給出1 3 8 11 15 null,2 null,返回1 2 3 8 11 15 null。解題思路 遍歷第二個鍊錶的每乙個節點,然後與第乙個節點的第乙個節點比較,如果第二個鍊錶節點的值小於第乙個,就插入到第乙個煉表裡,如果大於就到下乙個節點。...