链表总结

有序链表合并

21. 合并两个有序链表

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next

class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        dummy_head = ListNode(0)
        c, c1, c2 = dummy_head, l1, l2
        while c1 and c2:
            if c1.val <= c2.val:
                c.next = c1
                c1 = c1.next
            else:
                c.next = c2
                c2 = c2.next
            c = c.next

        if c1:
            c.next = c1
        if c2:
            c.next = c2

        return dummy_head.next

最后更新于