合并两个有序链表

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

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

 

代码思路:

这道题有三种解法,一种是不增加列表的情况下迭代,一种对比容易的是生成新的列表迭代,还有一个方法是递归。递归那个我没有看懂,在这里先记录下不增加列表的迭代和递归。

递归的话需要先对链表的第一个数进行对比,保证选择输出的链表的首个val是最小的。这个时候因为已经同向对比过了,接下来就是差为对比了。

class Solution:
    
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        if not l1:
            return l2
        elif not l2:
            return l1
        if l1.val > l2.val:
            l1, l2 = l2, l1
        head = l1    
        while l2:
            if not l1.next:
                l1.next = l2
                break
            if l1.next.val > l2.val:
                tmp = l2.next
                l2.next = l1.next
                l1.next = l2
                l2 = tmp
            l1 = l1.next 
                        
        return head
        """
        if l1 is None:
            return l2
        if l2 is None:
            return l1
        p=None
        if l1.val < l2.val:
            p=l1
            p.next=self.mergeTwoLists(l1.next,l2)
        else:
            p=l2
            p.next=self.mergeTwoLists(l1,l2.next)
        return p
            """

 

posted on 2019-04-11 18:37  雪原那么远  阅读(117)  评论(0编辑  收藏  举报

导航