topic
Merge two ascending linked lists into a new ascending linked list and return. The new linked list is formed by splicing all the nodes of the given two linked lists.
输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]
输入:l1 = [], l2 = []
输出:[]
输入:l1 = [], l2 = [0]
输出:[0]
recursion
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
def mergeTwoLists(list1: ListNode, list2: ListNode) -> ListNode:
if list1 is None:
return list2
if list2 is None:
return list1
if list1.val < list2.val:
list1.next = mergeTwoLists(list1.next, list2)
return list1
else:
list2.next = mergeTwoLists(list1, list2.next)
return list2
Time complexity: O(n+m), where n and m are the lengths of the two linked lists respectively. Because each recursion call removes the head node of l1 or l2 (until at least one linked list is empty), the function mergeTwoList will recursively call each node at most once. Therefore, the time complexity depends on the length of the merged linked list, which is O(n+m).
Space complexity: O(n+m), where n and m are the lengths of the two linked lists respectively. When calling mergeTwoLists function recursively, it needs to consume stack space, and the size of stack space depends on the depth of recursive call. The mergeTwoLists function is called at most n+m times at the end of the recursive call, so the space complexity is O(n+m).
iterate
1. Set the virtual node preHead to store the merged linked list
2. Start the comparison from the value of the head node of l1 and l2, and move the head node of the linked list with the smaller value until the head node of a linked list points to empty
3. Connect the remaining linked list
def mergeTwoLists(list1: ListNode, list2: ListNode) -> ListNode:
preHead = ListNode(-1)
prev = preHead
while list1 and list2:
if list1.val <= list2.val:
prev.next = list1
list1 = list1.next
else:
prev.next = list2
list2 = list2.next
prev = prev.next
prev.next = list1 if list1 is not None else list2
return preHead.next
The simple iterative implementation of merging two ordered linked lists is a bit abstract and difficult to understand. It can be compared with the simple iterative implementation of merging two ordered arrays, which is much easier to understand.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。