LeetCode之 21. Merge Two Sorted Lists

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

class Solution(object):
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        head = l = ListNode(0)
        while l1 and l2 :
            if l1.val <= l2.val :
                l.next = l1
                l1=l1.next
            else :
                l.next = l2
                l2=l2.next
            l=l.next
        l.next = l1 or l2
        return head.next

猜你喜欢

转载自blog.csdn.net/weixin_40748006/article/details/80050728