Python, LintCode, 165. 合并两个排序链表

"""
Definition of ListNode
class ListNode(object):
    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""

class Solution:
    """
    @param l1: ListNode l1 is the head of the linked list
    @param l2: ListNode l2 is the head of the linked list
    @return: ListNode head of linked list
    """
    def mergeTwoLists(self, l1, l2):
        # write your code here
        if l1 == None:
            if l2 == None:
                return None
            else:
                return l2
        elif l2 == None:
            return l1
            
        prehead = ListNode(None)
        tmp = prehead
        while l1 != None and l2 != None:
            if l1.val < l2.val:
                tmp.next = l1
                tmp = l1
                l1 = l1.next
            else:
                tmp.next = l2
                tmp = l2
                l2 = l2.next
        if l1 == None:
            tmp.next = l2
        elif l2 == None:
            tmp.next = l1
            
        return prehead.next

猜你喜欢

转载自blog.csdn.net/u010342040/article/details/80264101
今日推荐