[Leetcode] 21. Merge Two Sorted Lists

来源:互联网 发布:js获取json中的数据 编辑:程序博客网 时间:2024/06/08 06:16

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

合并两个有序链表,只允许通过两个链表相互插接的方式

自己写怎么也写不出,后来才知道用递归做,既简洁又高效率。

# Definition for singly-linked list.# class ListNode(object):#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution(object):    def mergeTwoLists(self, l1, l2):        """        :type l1: ListNode        :type l2: ListNode        :rtype: ListNode        """        if not l1:            return l2        if not l2:            return l1                if l1.val < l2.val:            l1.next = self.mergeTwoLists(l1.next,l2)            return l1        else:            l2.next = self.mergeTwoLists(l1,l2.next)            return l2