链表排序(Sort List)

这篇博客介绍了如何使用Python实现链表的二路归并排序,该方法具有O(nlogn)的时间复杂度和常数级的空间复杂度。详细阐述了排序算法的具体实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

链表排序所用到的语言和方法:

1、语言:Python
2、时间复杂度O(nlogn)
3、空间复杂度为常数
4、用的排序算法:二路归并排序

具体实现算法如下所示:

 class ListNode(object):
     def __init__(self, x):
         self.val = x
         self.next = None
def sortList(head):
        if head == None or head.next == None:
            return head

        pre = None
        slow = head
        fast = head

        while fast != None and fast.next != None:
            pre = slow
            slow = slow.next
            fast = fast.next.next

        pre.next = None

        left = sortList(head)
        right = sortList(slow)

        return merge(left,right)

    def merge(left,right):
        res = ListNode(0)
        temp = res
        while left != None and right != None:
            if left.val <= right.val:
                temp.next = left
                temp = temp.next
                left = left.next
            else:
                temp.next = right
                temp = temp.next
                right = right.next

        if left != None:
            temp.next = left

        if right != None:
            temp.next = right

        return res.next
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值