The number of nodes in both lists is in the range [0, 50].
-100 <= Node.val <= 100
Both list1 and list2 are sorted in non-decreasing order.
Solutions
Solution 1: Recursion
First, we judge whether the linked lists $l_1$ and $l_2$ are empty. If one of them is empty, we return the other linked list. Otherwise, we compare the head nodes of $l_1$ and $l_2$:
If the value of the head node of $l_1$ is less than or equal to the value of the head node of $l_2$, we recursively call the function $mergeTwoLists(l_1.next, l_2)$, and connect the head node of $l_1$ with the returned linked list head node, and return the head node of $l_1$.
Otherwise, we recursively call the function $mergeTwoLists(l_1, l_2.next)$, and connect the head node of $l_2$ with the returned linked list head node, and return the head node of $l_2$.
The time complexity is $O(m + n)$, and the space complexity is $O(m + n)$. Here, $m$ and $n$ are the lengths of the two linked lists respectively.
1 2 3 4 5 6 7 8 91011121314151617
# Definition for singly-linked list.# class ListNode:# def __init__(self, val=0, next=None):# self.val = val# self.next = nextclassSolution:defmergeTwoLists(self,list1:Optional[ListNode],list2:Optional[ListNode])->Optional[ListNode]:iflist1isNoneorlist2isNone:returnlist1orlist2iflist1.val<=list2.val:list1.next=self.mergeTwoLists(list1.next,list2)returnlist1else:list2.next=self.mergeTwoLists(list1,list2.next)returnlist2
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */funcmergeTwoLists(list1*ListNode,list2*ListNode)*ListNode{iflist1==nil{returnlist2}iflist2==nil{returnlist1}iflist1.Val<=list2.Val{list1.Next=mergeTwoLists(list1.Next,list2)returnlist1}else{list2.Next=mergeTwoLists(list1,list2.Next)returnlist2}}