美文网首页Leetcode刷题笔记
第二十六天 Merge Two Sorted Lists

第二十六天 Merge Two Sorted Lists

作者: 业余马拉松选手 | 来源:发表于2018-09-14 21:23 被阅读0次

嗯,二十六天了
回家就先刷一题吧
最近事情更多了,插进去一件晋升的事情,总是压着一块石头似的

https://leetcode-cn.com/problems/merge-two-sorted-lists/description/

合并两个有序的链表

简单明了的方法,其实应该是递归
假设l1是空,直接返回l2
假设l2是空,直接返回l1

到这里,都比较简单的可以理解

那么接下来,如果l1的值小于l2的值,这时l1的应该指向的就是l1.next和l2合并的结果了,
嗯,这句话其实是“核心”
同样道理,如果l2的值小于l1的值,那么l2应该指向的是l1和l2.next的合并结果咯

嗯,如果能理解的话,代码就特别简单明了啦

# 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:
            return l2
        if l2 is None:
            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

相关文章

网友评论

    本文标题:第二十六天 Merge Two Sorted Lists

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