![bad8bb8307e065f840c655c9519437e4.png](https://i-blog.csdnimg.cn/blog_migrate/669c5d9e0ac1db6b49d6859c9f2ab8ef.jpeg)
描述解题思路
- 关键字: 两个/多个链表
- 模式识别: 用while循环,都不为空就常规处理,直到一个为空就把剩下的链接上就行;边界情况链表为空,考虑创建哑结点。
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = nextclass Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
merge_list_head = ListNode(0)
merge_list_pre = merge_list_head # 跟踪合并链表的尾节点
while l1 and l2: # 对比l1和l2对应值的大小,把值小的那个节点放入新链表,接着后移一位继续比较下一个节点值
if l1.val < l2.val:
merge_list_pre.next = l1 # 把值更小的l1节点加入合并链表
l1 = l1.next # 向后移动比较下一个节点大小
else:
merge_list_pre.next = l2
l2 = l2.next
merge_list_pre = merge_list_pre.next # 向后移动变成尾节点
merge_list_pre.next = l1 if l1 else l2 # 处理剩下的非空链表,因为两个链表已经排序过了,所以剩下的元素直接加入合并链表就行
return merge_list_head.next # 记得最后返回的时候不要哑结点
测试:
- 正常测试用例:1->2->4;1->3->4
- 不进入while循环: [];[0]
算法复杂度:
- 时间复杂度O(n):遍历两个链表
- 空间复杂度O(1): 常数空间放若干变量