[LeetCode21]合并两个有序链表 (Merge Two Sorted Lists)

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

e.g.:

输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
 
 
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        mylist=listnow=ListNode(0)
        while l1 and l2:
            if l1.val<l2.val:
                listnow.next=l1
                l1=l1.next
            else:
                listnow.next=l2
                l2=l2.next
            listnow=listnow.next
        listnow.next=l1 or l2
        return mylist.next

猜你喜欢

转载自blog.csdn.net/weixin_42058047/article/details/80070750