美文网首页
Leetcode-21题:Merge Two Sorted Li

Leetcode-21题:Merge Two Sorted Li

作者: 八刀一闪 | 来源:发表于2016-09-24 16:52 被阅读20次

    题目:

    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.

    代码:

    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        head = ListNode(None)
        p = head
    
        while l1!=None and l2!=None:
            p.next = l1
            if l1.val < l2.val:
                p = p.next
                l1 = l1.next
            else:
                p.next = l2
                p = p.next
                l2 = l2.next
    
        if l1 != None:
            p.next = l1
        if l2 != None:
            p.next = l2
    
        return head.next
    

    相关文章

      网友评论

          本文标题:Leetcode-21题:Merge Two Sorted Li

          本文链接:https://www.haomeiwen.com/subject/ftvxyttx.html