2-3

21.合并两个有序链表

将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

示例:

输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4

An easy python solution:

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

class Solution(object):
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        dummy = cur = 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 or l2
        return dummy.next

分析:

  • 双指针dummy = cur = ListNode(0)的目的:

    一个用来构造结果链表(cur),另一个用来返回最终的结果链表(dummy)。

  • 注意while循环的入口条件是l1 and l2

  • 程序的倒数第二行cur.next = l1 or l2

    因为while循环跳出之后,l1和l2中必至少有一个是None,此处的or就相当于是求并集的意思(None就相当于是空集,一个空集和任意一个集合求并,结果必为该集合本身),因此使用or可以很好地将l1或l2中剩余的部分衔接到cur后面。

原文地址:https://www.cnblogs.com/tbgatgb/p/11105055.html