16 合併兩個排序的鍊錶

2021-10-01 16:31:21 字數 1825 閱讀 6287

題目描述

輸入兩個單調遞增的鍊錶,輸出兩個鍊錶合成後的鍊錶,當然我們需要合成後的鍊錶滿足單調不減規則。

python 方法1: 遞迴:

class

solution

:# 返回合併後列表

defmerge

(self, phead1, phead2)

:if phead1 is

none

:return phead2

elif phead2 is

none

:return phead1

elif phead1.val < phead2.val:

phead1.

next

= self.merge(phead1.

next

, phead2)

return phead1

else

: phead2.

next

= self.merge(phead1, phead2.

next

)return phead2

python 方法2:非遞迴:

class

solution

:# 返回合併後列表

defmerge

(self, phead1, phead2)

: head =

none

# 存在至少乙個鍊錶為空

if phead2 is

none

:return phead1

elif phead1 is

none

:return phead2

else

:# 確定頭節點

while phead1 and phead2:

if phead1.val >= phead2.val:

head = phead2

phead2 = phead2.

next

else

: head = phead1

phead1 = phead1.

next

break

cur = head

while phead1 and phead2:

if phead1.val >= phead2.val:

cur.

next

= phead2

phead2 = phead2.

next

cur = cur.

next

else

: cur.

next

= phead1

phead1 = phead1.

next

cur = cur.

next

# 比較完只有乙個鍊錶不為空或者兩個鍊錶都為空

if phead1:

cur.

next

= phead1

if phead2:

cur.

next

= phead2

return head

c++: 遞迴:

class

solution

else

if(phead2 ==

null

)else

if(phead1-

>val < phead2-

>val)

else}}

;

16 合併兩個排序的鍊錶

題目 輸入兩個單調遞增的鍊錶,輸出兩個鍊錶合成後的鍊錶,當然我們需要合成後的鍊錶滿足單調不減規則。思路 與歸併排序思路相同。用到了乙個小技巧,宣告頭節點時,不宣告為null,使資料域為0,返回時返回head.next,這樣在 不需要先給head賦值,比較簡潔。public class solutio...

16 合併兩個排序的鍊錶

輸入兩個單調遞增的鍊錶,輸出兩個鍊錶合成後的鍊錶,當然我們需要合成後的鍊錶滿足單調不減規則。總結 要建立乙個新的頭結點,如果直接在l1 l2 上修改,鍊錶就會被更改,還要涉及到儲存結點,會使得問題複雜化。建立新的頭結點之後,每次都向後挪動一位,並且插入l1 l2 中的小值,對應的鍊錶挪動一位。tip...

16 合併兩個排序的鍊錶 python

輸入兩個單調遞增的鍊錶,輸出兩個鍊錶合成後的鍊錶,當然我們需要合成後的鍊錶滿足單調不減規則。1 class solution 2 返回合併後列表 3def merge self,phead1,phead2 4 write code here 5 dummy p listnode 1 6while p...