Sort List Leetcode Python

Sort a linked list in O(n log n) time using constant space complexity.

这道题要求时间为nlogn我们联想到quick sort 或者mergesort这里采用mergesort

quick sort的最差为n^2 在逆序的时候。


和array mergesort不同的是这里找Mid 需要用两个pointer一个fast 一个slow

当fast.走到底的时候slow 刚刚好走到中间 其他的做法与array的mergesort一样。

代码如下 

class ListNode:
    def __init__(self,val):
        self.val=val
        self.next=None


head=root=ListNode(0)
head.next=ListNode(10)
head=head.next
head.next=ListNode(22)
head=head.next
head.next=ListNode(3)
head=head.next
head.next=ListNode(1)
head=head.next
head.next=ListNode(2)
head=head.next
head.next=ListNode(4)

def printL(root):
    while root:
        print root.val
        root=root.next


printL(root)

def merge(left,right):
    dummy=ListNode(0)
    newhead=dummy
    if left==None:
        return right
    if right==None:
        return left
        
    while left and right:
        if left.val<right.val:
            newhead.next=ListNode(left.val)
            left=left.next
        else:
            newhead.next=ListNode(right.val)
            right=right.next
        newhead=newhead.next
    if left:
        newhead.next=left
    if right:
        newhead.next=right
    return dummy.next

newhead=merge(root,root)
printL(newhead)




def mergesort(root):
    if root.next==None or root==None:
        return root

    fast=root
    slow=root
    
    while fast.next and fast.next.next:
        fast=fast.next.next
        slow=slow.next
    left=root
    right=slow.next
    slow.next=None
    
    left=mergesort(left)
    right=mergesort(right)
    return merge(left,right)

newhead=mergesort(root)
printL(newhead)

    


    

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值