21. 合并两个有序链表
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例 1:
输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]
示例 2:
输入:l1 = [], l2 = []
输出:[]
示例 3:
输入:l1 = [], l2 = [0]
输出:[0]
提示:
两个链表的节点数目范围是 [0, 50]
-100 <= Node.val <= 100
l1 和 l2 均按 非递减顺序 排列
解法1:递归
-
首先明确函数的作用是返回拼接后的链表的头结点
-
边界条件是其中一个链表为空
-
f ( l i s t 1 , l i s t 2 ) = { l i s t 1 a n d l i s t 1. n e x t = f ( l i s t 1. n e x t , l i s t 2 ) , i f l i s t 1. v a l < = l i s t 2. v a l , l i s t 2 a n d l i s t 2. n e x t = f ( l i s t 1 , l i s t 2 , n e x t ) , o t h e r w i s e f(list1, list2) = \begin{cases} list1\ and\ list1.next = f(list1.next, list2),\ if\ list1.val <= list2.val, \\ list2\ and\ list2.next = f(list1, list2,next),\ otherwise\\ \end{cases} f(list1,list2)={list1 and list1.next=f(list1.next,list2), if list1.val<=list2.val,list2 and list2.next=f(list1,list2,next), otherwise
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
if not list1:
return list2
elif not list2:
return list1
if list1.val <= list2.val:
list1.next = self.mergeTwoLists(list1.next, list2)
return list1
else:
list2.next = self.mergeTwoLists(list1, list2.next)
return list2
解法2:迭代
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
head = cur = ListNode()
while list1 and list2:
if list1.val <= list2.val:
cur.next = list1
list1 = list1.next
else:
cur.next = list2
list2 = list2.next
cur = cur.next
if not list1:
cur.next = list2
else:
cur.next = list1
return head.next