将两个有序链表合并为一个新的有序链表并返回。新链表是经过拼接给定的两个链表的全部节点组成的。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