將兩個有序鏈表合併爲一個新的有序鏈表並返回。新鏈表是經過拼接給定的兩個鏈表的全部節點組成的。code
示例:遞歸
輸入:1->2->4, 1->3->4 輸出:1->1->2->3->4->4 輸入:1->2->4, 5 輸出:1->2->4->5
三種方法:it
經過代碼以下:io
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # 方法一: # 尾插法,更改原始鏈表。時間複雜度O(n),空間複雜度O(1) def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: thead = ListNode(-1) # 開闢一個表頭結點,用於返回時候使用 t = thead while l1 and l2: if l1.val<=l2.val: t.next = l1 t = l1 l1 = l1.next else: t.next = l2 t = l2 l2 = l2.next # 如下是把沒走完的鏈表添加到尾部 if l1: t.next = l1 if l2: t.next = l2 return thead.next # # 方法二: # # 原鏈表不變,另開闢新空間。時間複雜度O(n+m),空間複雜度O(n+m) # def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: # head = ListNode(0) # temp = head # c2 = l2 # while l1 and c2: # if l1.val <= c2.val: # t = ListNode(l1.val) # temp.next = t # temp = t # l1 = l1.next # else: # t = ListNode(c2.val) # temp.next = t # temp = t # c2 = c2.next # while l1: # temp.next = l1 # temp = l1 # l1 = l1.next # while c2: # temp.next = c2 # temp = c2 # c2 = c2.next # return head.next # # 方法三:遞歸,這個答案是抄的,沒懂。。。 # def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: # # 如有一個爲空,則直接返回另外一個 # if not l1: # return l2 # if not l2: # return l1 # # 遞歸能夠理解爲以後的狀況都處理好了,只須要解決好當前這步就好了 # if l1.val <= l2.val: # l1.next = self.mergeTwoLists(l1.next, l2) # return l1 # else: # l2.next = self.mergeTwoLists(l1, l2.next) # return l2