1 题目描述
来源:力扣(LeetCode)
输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。
2 解题思路1
3 代码实现(Python3)
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
cur = dum = ListNode(0)
while l1 and l2:
if l1.val < l2.val:
cur.next, l1 = l1, l1.next
else:
cur.next, l2 = l2, l2.next
cur = cur.next
cur.next = l1 if l1 else l2
return dum.next
4 复杂度分析
- 时间复杂度 O(M+N) : M, N 分别为链表 l1,l2的长度,合并操作需遍历两链表。
- 空间复杂度 O(1) :双指针 dum,cur使用常数大小的额外空间。
深入了解复杂度:数据分析学习总结笔记11:空间复杂度和时间复杂度