難度:簡單
題目描述:
思路總結:迭代思路能想到,類似合併陣列,但是遞迴方法就有點精彩了,需要細細品味。其中的邊界條件缺一不可。
題解一:
第一版
題解一結果:# definition for singly-linked list.
# class listnode:
# def __init__(self, x):
# self.val = x
# self.next = none
class
solution
:def
mergetwolists
(self, l1: listnode, l2: listnode)
-> listnode:
#思路:有點像合併陣列
cur1 = l1
cur2 = l2
head = listnode(0)
res = head
while cur1 and cur2:
if cur1.val >= cur2.val:
head.
next
= cur2
cur2 = cur2.
next
else
: head.
next
= cur1
cur1 = cur1.
next
head = head.
next
if cur1:
head.
next
= cur1
else
: head.
next
= cur2
return res.
next
題解二:(遞迴)
class
solution
:def
mergetwolists
(self, l1: listnode, l2: listnode)
-> listnode:
#思路:遞迴,屬實精彩。
ifnot l1:
return l2
elif
not l2:
return l1
elif l1.val < l2.val:
l1.next
= self.mergetwolists(l1.
next
, l2)
return l1
else
: l2.
next
= self.mergetwolists(l1, l2.
next
)return l2
21 合併兩個有序鍊錶
將兩個有序鍊錶合併為乙個新的有序鍊錶並返回。新煉表是通過拼接給定的兩個鍊錶的所有節點組成的。示例 輸入 1 2 4,1 3 4 輸出 1 1 2 3 4 4 原本想的是用19題的結構陣列那種方法來做 分別遍歷兩個鍊錶,建立結構儲存原始索引,val和指標,氣泡排序這個結構,更新索引,按照索引建立新的n...
21 合併兩個有序鍊錶
合併兩個有序鍊錶 將兩個有序鍊錶合併為乙個新的有序鍊錶並返回。新煉表是通過拼接給定的兩個鍊錶的所有節點組成的。示例 輸入 1 2 4,1 3 4輸出 1 1 2 3 4 4比較簡單,比較大小,重新排序即可。created by hints on 2019 1 9.include using name...
21 合併兩個有序鍊錶
將兩個有序鍊錶合併為乙個新的有序鍊錶並返回。新煉表是通過拼接給定的兩個鍊錶的所有節點組成的。輸入 1 2 4,1 3 4 輸出 1 1 2 3 4 4先確定合併鍊錶第乙個節點 在迴圈中同時遍歷兩個鍊錶,將後面其餘節點逐次比較,依大小次序連線到首節點之後,迴圈結束後可能有乙個鍊錶未遍歷完,將這個鍊錶剩...