[leetcode]21. Merge Two Sorted Lists

突然发现代码开头的注释取消注释就是ListNode的定义,可以本地调试了。。。

这道题注意两个链表可以同时为None.

 

Runtime: 44 ms, faster than 86.67% of Python3 online submissions forMerge Two Sorted Lists.
Memory Usage: 13 MB, less than 86.39% of Python3 online submissions forMerge Two Sorted Lists.
 

Submission Detail

208 / 208 test cases passed.
Status: 

Accepted

Runtime: 44 ms
Memory Usage: 13 MB
Submitted: 0 minutes ago

 

class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        #0
        if l1 == None and l2 == None:
            return l1
        if l1 == None:
            return l2
        if l2 == None:
            return l1
        # init
        if l1.val >= l2.val:
            ret = ListNode(l2.val)
            ret.next = None
            l2 = l2.next
        else:
            ret = ListNode(l1.val)
            ret.next = None
            l1 = l1.next
        retu =ret
        # normal
        while (l1 != None or l2 != None):
            # none
            if l1 == None:
                ret.next = l2
                return retu
            if l2 == None:
                ret.next = l1
                return retu
            # normal
            if l1.val >= l2.val:
                ret.next = ListNode(l2.val)
                ret = ret.next
                l2 = l2.next
            else:
                ret.next = ListNode(l1.val)
                ret = ret.next
                l1 = l1.next
        return retu

 

posted @ 2019-05-27 23:52  夜歌乘年少  阅读(198)  评论(0编辑  收藏  举报