原題:
將兩個有序鏈表合併爲一個新的有序鏈表並返回。新鏈表是通過拼接給定的兩個鏈表的所有節點組成的。
示例:
輸入:1->2->4, 1->3->4
輸出:1->1->2->3->4->4
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/merge-two-sorted-lists
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
解法一:(遞歸法)
在我看來,遞歸的思路是非常簡單的,我們只需要將遞歸函數當成已經處理完畢的一個引用變量,由於最後遞歸函數是會遞歸到最簡單的情況的之後在遞歸回去,所以我們只需要處理python (l1 == None or l2 == None)
這種情況其他複雜情況直接往下繼續遞歸。
程序如下:
程序一:
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if l1 == None or l2==None:
if l1 != None:
return l1
elif l2 != None:
return l2
else:
return None
if l1.val > l2.val:
l2.next = self.mergeTwoLists(l1,l2.next)
return l2
else:
l1.next = self.mergeTwoLists(l1.next,l2)
return l1
程序二:
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if l1 and l2:
if l1.val > l2.val: l1, l2 = l2, l1
l1.next = self.mergeTwoLists(l1.next, l2)
return l1 or l2
解法二:(迭代)
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
pro = ans = ListNode(0)
if l1 == None or l2==None:
if l1 != None:
return l1
elif l2 != None:
return l2
else:
return None
while l1 != None and l2 != None:
if l1.val > l2.val:
ans.next = l2
l2 = l2.next
ans = ans.next
else:
ans.next = l1
l1 = l1.next
ans = ans.next
if l1 == None or l2==None:
if l1 != None:
ans.next = l1
elif l2 != None:
ans.next = l2
return pro.next