劍指offer 11 合併兩個有序鍊錶

2021-10-04 20:02:19 字數 2061 閱讀 1468

題目描述:

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

# class listnode:

# def __init__(self, x):

# self.val = x

# self.next = none

class

solution

:# 返回合併後列表

defmerge

(self, phead1, phead2)

:# write code here

# 先判斷兩個頭結點是否為空

if phead1 ==

none

:return phead2

if phead2 ==

none

:return phead1

# 代替最小節點

newhead = phead1 if phead1.val < phead2.val else phead2

# 儲存當前兩個頭結點

tmp1 = phead1

tmp2 = phead2

#判斷最小節點是哪乙個,然後移動指標指向下乙個元素

if newhead == tmp1:

tmp1 = tmp1.

next

else

: tmp2 = tmp2.

next

previous = newhead

# 迴圈比較

while tmp1 and tmp2:

# 比較最小元素的下乙個節點和另乙個煉表頭節點大小

if tmp1.val < tmp2.val:

previous.

next

= tmp1

previous = tmp1 #也可以直接加previous = previous.next

tmp1 = tmp1.

next

else

: previous.

next

= tmp2

previous = tmp2

tmp2 = tmp2.

next

# 迴圈結束,然後把剩餘元素補上

if tmp1 ==

none

: previous.

next

= tmp2

else

: previous.

next

= tmp1

return newhead

方法二:遞迴法

class

solution

:# 返回合併後列表

defmerge

(self, phead1, phead2)

:# write code here

if phead1 ==

none

:return phead2

if phead2 ==

none

:return phead1

if phead1.val < phead2.val:

phead1.

next

= self.merge(phead1.

next

,phead2)

return phead1

else

: phead2.

next

= self.merge(phead1,phead2.

next

)return phead2

總結:比較兩個鍊錶大小的時候,可以設定乙個頭節點cur,用來儲存每一次比較後的值,並且設定兩個指標p1,p2,分別遍歷兩個鍊錶。

1、如果p1.val < p2.val:cur.next = p1頭節點指向下乙個較小的節點;cur = cur.next 更新cur的值;p1 = p1.nextp1在指向下乙個元素;

劍指offer 合併兩個有序鍊錶

依次比較兩個鍊錶的首結點,取較小的的結點放到第三個鍊錶尾,同時移動較小節點所在鍊錶的指標指向下乙個節點。步驟一結果會有乙個鍊錶先遍歷結束 第三個鍊錶尾結點指向剩餘未遍歷結束的鍊錶 返回第三個鍊錶首結點 struct listnode class solution else merlist merli...

劍指offer 合併兩個有序鍊錶

題目描述 輸入兩個單調遞增的鍊錶,輸出兩個鍊錶合成後的鍊錶,當然我們需要合成後的鍊錶滿足單調不減規則。參考思路 逐個比較兩個鍊錶的第乙個結點,將結點值小的那個結點新增到乙個新的鍊錶上。直到最後乙個兩個鍊錶都合併到新的鍊錶上結束。參考 public class listnode public clas...

劍指offer 合併兩個有序鍊錶 python

方法一 迭代 簡化 方法二 遞迴 題目 將兩個有序鍊錶合併為乙個新的有序鍊錶並返回。題目位置 位置 示例 輸入 1 2 4,1 3 4 輸出 1 1 2 3 4 4class solution object def mergetwolists self,l1,l2 type l1 listnode ...