合併兩個排序的鍊錶

2021-08-10 13:57:03 字數 1357 閱讀 1908

題目描述:

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

答案:非遞迴

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

# class listnode:

# def __init__(self, x):

# self.val = x

# self.next = none

class solution:

# def merge(self,phead1, phead2):

# write code here

if phead1==none and phead2==none:

return none

if phead1==none:

return phead2

if phead2==none:

return phead1

phead3 = listnode(0)

p1 = phead1

p2 = phead2

if phead1.val < phead2.val:

phead3 = phead1

p1 = phead1.next

else:

phead3 = phead2

p2 = phead2.next

p3 = phead3#每次指向要新合併的節點

while p1 and p2:

if p1.val < p2.val:

p3.next = p1

p1 = p1.next

else:

p3.next = p2

p2 = p2.next

p3 = p3.next

if p1:

p3.next = p1

else:

p3.next = p2

return phead3

遞迴

def merge(phead1, phead2):

# write code here

if phead1 == none:

return phead2

elif phead2 == none:

return phead1

if phead1.val <= phead2.val:

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

return phead1

else:

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

return phead2

合併兩個排序鍊錶

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。解題思路 遍歷第二個鍊錶的每乙個節點,然後與第乙個節點的第乙個節點比較,如果第二個鍊錶節點的值小於第乙個,就插入到第乙個煉表裡,如果大於就到下乙個節點。...