呓语Beta 2.0 首页 镜头后 灶台前 捐赠者名单 有趣的小站

leetcode 21 Merge Two Sorted Lists

文档信息

leetcode 21 Merge Two Sorted Lists

解法一

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        head = p = None
        p1 = l1
        p2 = l2
        
        if not (p1 and p2):
            return p1 or p2
        
        while p1 != None and p2 != None:
            curr = None
            if p1.val <= p2.val:
                curr = p1
                p1 = p1.next
            else:
                curr = p2
                p2 = p2.next
                
            if head == None:
                head = p = curr
            else:
                p.next = curr
                p = curr
                p.next = None
                
        if p1 != None:
            p.next = p1
        elif p2 != None:
            p.next = p2
            
        return head

note

付费支持

由于本网站没有广告和任何形式的收入来源,希望获得您的资助。每篇技术性文章和每期shellcasts视频定价人民币1元,在您付费后可以任意观看和下载。

可以使用支付宝手机钱包扫描下方的二维码进行付款操作或者用支付宝转帐给richard.ma.19850509@gmail.com,谢谢!

Fork me on GitHub