劍指offer16 合併兩個排序的鍊錶

2022-07-09 07:24:08 字數 1657 閱讀 2324

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

輸入      ,

返回值 

排序鍊錶合併

#遞迴法

#-*- coding:utf-8 -*-

#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

if phead1.valnewhead=phead1

phead1=phead1.next

newhead.next=self.merge(phead1, phead2)

else

: newhead=phead2

phead2=phead2.next

newhead.next=self.merge(phead1, phead2)

return newhead

#遞迴比較複雜,可以搭配debug:

a1=listnode(1)

b1=listnode(3)

c1=listnode(5)

a2=listnode(2)

b2=listnode(4)

c2=listnode(6)

a1.next=b1

b1.next=c1

a2.next=b2

b2.next=c2

c=solution()

c.merge(a1,a2)

#非遞迴法

#-*- coding:utf-8 -*-

#class listnode:

#def __init__(self, x):

#self.val = x

#self.next = none

class

solution:

#返回合併後列表

defmerge(self, phead1, phead2):

newhead=listnode(0) #隨便找個頭節點

tmp=newhead #記錄當前插入位置的指標

while phead1 and

phead2:

if phead1.valtmp.next=phead1

phead1=phead1.next

else

: tmp.next=phead2

phead2=phead2.next

tmp=tmp.next

ifphead1:

tmp.next=phead1

ifphead2:

tmp.next=phead2

return newhead.next

劍指offer 16 合併兩個排序的鍊錶

題目 輸入兩個單調遞增的鍊錶,輸出兩個鍊錶合成後的鍊錶,當然我們需要合成後的鍊錶滿足單調不減規則。思路 先對兩個鍊錶用容器進行 然後在容器中對容器內的元素進行排序,最後進行合成鍊錶。struct listnode class solution while phead2 null sort vec.b...

劍指offer 16 合併兩個排序的鍊錶

輸入兩個單調遞增的鍊錶,輸出兩個鍊錶合成後的鍊錶,當然我們需要合成後的鍊錶滿足單調不減規則。時間限制 1秒 空間限制 32768k 熱度指數 366049 本題知識點 鍊錶 新建乙個鍊錶,然後兩個煉表頭元素比較,取較小值加入到鍊錶中 做這道題做了很久,雖然很簡單,但總報錯說死迴圈,後來發現原來是指標...

《劍指Offer》16 合併兩個排序的鍊錶

題目 16.合併兩個排序的鍊錶 知識點 魯棒性 題目描述 輸入兩個單調遞增的鍊錶,輸出兩個鍊錶合成後的鍊錶,當然我們需要合成後的鍊錶滿足單調不減規則。解題思路 解法一 使用迴圈實現,即首先排除特殊情況 兩個鍊錶同時為空,或其中之一為空 其次同時對兩個鍊錶進行遍歷,將值較小的結點接到輸出鍊錶末尾即可。...