Lintcode 165. 合并两个排序链表

我的代碼如下:

    def mergeTwoLists(self, l1, l2):
        if l1 == None:
            return l2
        if l2 == None:
            return l1
        res = ListNode(None)
        while l1 and l2:
            if l1.val <= l2.val:
                print(l1.val)
                res = l1 //不該直接把l1赋给res 应该采取res.next的形式
                l1 = l1.next
                res = res.next //不然链表在后移的时候会覆盖现在的节点
            else:
                res = l2
                l2 = l2.next
                res = res.next
        if l1:
            res.next = l1
        if l2:
            res.next = l2
        return res

答案:

class Solution(object):
    '''
    题意:合并两个有序链表
    '''
    def mergeTwoLists(self, l1, l2):
        dummy = ListNode(0)
        tmp = dummy
        while l1 != None and l2 != None:
            if l1.val < l2.val:
                tmp.next = l1
                l1 = l1.next
            else:
                tmp.next = l2
                l2 = l2.next
            tmp = tmp.next
        if l1 != None:
            tmp.next = l1
        else:
            tmp.next = l2
        return dummy.next

猜你喜欢

转载自blog.csdn.net/Sallywa/article/details/82763966
今日推荐