合併兩個排序鍊錶

2021-10-04 05:46:03 字數 951 閱讀 6028

思路很簡單,依次比較最小值,把小的加入。有乙個注意的地方是可以有個頭結點之類的點在前面,只要返回的時候,返回頭節點之後的點就可以通過。

定義新的結點是phead = listnode(5),代表輸入的初始值val是5.

# class listnode(object):

# def __init__(self, x):

# self.val = x

# self.next = none

class

solution

(object):

defmergetwolists

(self, l1, l2)

: phead = listnode(5)

phead1 = phead

ifnot l1 and

not l2:

return

ifnot l1:

return l2

ifnot l2:

return l1

while l1 !=

none

and l2 !=

none

:if l1.val <= l2.val:

phead1.

next

, l1 = l1, l1.

next

phead1 = phead1.

next

else

: phead1.

next

= l2

phead1 = phead1.

next

l2 = l2.

next

phead1.

next

= l2 if l2 else l1

return phead.

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