链表排序 Python

插入排序

class Solution(object):
    def insertionSortList(self, head):
        p = new_s =ListNode(None) #插入的有可能在头结点前面
        new_s.next = head
        cur = head
        while cur and cur.next:
            val = cur.next.val
            if val>cur.val:
                cur = cur.next
                continue #如果是排好的,继续往后
            if p.next.val > val: #p后面是之前节点插入的位置,p大则重头找
                p = new_s
            while p.next.val<val: #找到p小于,p.next大于该数
                p = p.next
            new = cur.next
            cur.next = new.next
            new.next = p.next
            p.next = new
        return new_s.next

归并排序

class Solution(object):
    def sortList(self, head):
        if not head or not head.next: 
            return head

        slow, fast = head, head.next
        while fast and fast.next:
            fast, slow = fast.next.next, slow.next
        mid, slow.next = slow.next, None 

        left = self.sortList(head)
        right = self.sortList(mid)
        h = res = ListNode(None)
        while left and right:
            if left.val < right.val: 
                h.next, left = left, left.next
            else: 
                h.next, right = right, right.next
            h = h.next
        h.next = left if left else right
        return res.next

快速排序

class Solution(object):
    def sortList(self, head):
        hat = ListNode(None)
        hat.next = head
        quick_sort(hat, None)
        return hat.next

# requirement: hat is not None
def quick_sort(hat, tail):
    if hat.next is tail or hat.next.next is tail:
        return

    hat1, hat2, hat3 = hat, hat.next, ListNode(None)
    tail1, tail2, tail3 = hat1, hat2, hat3
    p, pivot = hat2.next, hat2.val
    while p is not tail:
        if p.val < pivot:
            tail1.next, tail1, p = p, p, p.next
        elif p.val == pivot:
            tail2.next, tail2, p = p, p, p.next
        else:
            tail3.next, tail3, p = p, p, p.next

    # Caution: DO NOT change the order of these three line codes below. 
    tail3.next = tail
    tail2.next = hat3.next
    tail1.next = hat2

    quick_sort(hat1, hat2)
    quick_sort(tail2, tail)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值