合并有序链表(python版)

合并有序链表

http://www.nowcoder.com/questionTerminal/a479a3f0c4554867b35356e0d57cf03d

跟合并有序数组差不多套路,就是数据结构麻烦些。
思路:
先选出第一个节点,然后遍历两个链表,把小的作为当前节点的下一个节点,一直到其中一个链表遍历完,这时候把另一个链表直接接上。

当然实现起来有递归和非递归版本,看你喜欢哪个啦,都没毛病,不过递归可能代码更短小精湛些。
代码1(非递归版):

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 not l1: return l2
        if not l2: return l1
        cur = dump = ListNode(0)
        while l1 and l2:
            if l1.val >= l2.val:
                cur.next = l2
                l2 = l2.next
                cur = cur.next
            else:
                cur.next = l1
                l1 = l1.next
                cur = cur.next
        cur.next = l1 if l1 else l2
        return  dump.next

代码2(递归版):

class Solution:
    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:
            ret = l1
            ret.next = self.mergeTwoLists(l1.next, l2)
        else:
            ret = l2
            ret.next = self.mergeTwoLists(l1, l2.next)
        return ret

麻豆出品,必出精品!

全部评论
这也能有车?
点赞 回复
分享
发布于 2021-03-31 14:42
我爱麻豆 麻豆爱我钱
点赞 回复
分享
发布于 2021-04-08 18:40
滴滴
校招火热招聘中
官网直投
递归版牛逼
点赞 回复
分享
发布于 2021-07-10 19:21

相关推荐

点赞 评论 收藏
转发
投递腾讯云智研发等公司9个岗位
点赞 评论 收藏
转发
19 收藏 评论
分享
牛客网
牛客企业服务