HOT 100 › 索引 › B7 链表 Linked List
LC 21合并两个有序链表Merge Two Sorted Lists 简单
将两条升序链表合并为一条升序链表并返回头节点。
思路 哑结点 + 双指针每次摘较小头节点尾插,余链直接接上。时间 O(m+n)。
class Solution: def mergeTwoLists(self, l1, l2): dummy = cur = ListNode() 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 dummy.next