美文网首页
LeetCode-21(合并两个有序链表)(Python)

LeetCode-21(合并两个有序链表)(Python)

作者: TinyShu | 来源:发表于2018-09-09 15:13 被阅读0次
    image.png
    解法一(60 ms 89.73%):
    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution:
        def mergeTwoLists(self, l1, l2):
            """
            :type l1: ListNode
            :type l2: ListNode
            :rtype: ListNode
            """
            if l1 is None and l2 is None:
                return None
            new_list=ListNode(0)
            pre=new_list
            while l1 is not None and l2 is not None:
                if l1.val<l2.val:      
                    pre.next=l1
                    l1=l1.next
                else:
                    pre.next=l2
                    l2=l2.next  
                pre=pre.next
            if l1 is not None:
                pre.next=l1
            if l2 is not None:
                pre.next=l2
            return new_list.next
    

    相关文章

      网友评论

          本文标题:LeetCode-21(合并两个有序链表)(Python)

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