leetcode148. 排序链表

归并排序的思想,先对链表进行对半切割,之后再进行重组。

def sortList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head or not head.next:
            return head
        fast,slow = head.next,head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
        mid,slow.next = slow.next,None
        left,right = self.sortList(head),self.sortList(mid)
        dummy = res = ListNode(0)
        while left and right:
            if left.val < right.val:
                dummy.next = left
                left = left.next
            else:
                dummy.next = right
                right = right.next
            dummy = dummy.next
        dummy.next = left if left else right
        return res.next

三路快排实现

def sortList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        def quick_sort(head):
            if not head or not head.next:
                return head
            slow,fast = head, head.next
            while fast and fast.next:
                slow = slow.next
                fast = fast.next.next
            val = slow.val
            h1 = t1 = ListNode(0)
            h2 = t2 = ListNode(0)
            h3 = t3 = ListNode(0)
            cur = head
            while cur:
                tmp = cur.next
                if cur.val < val:
                    cur.next = None
                    t1.next = cur
                    t1 = t1.next
                elif cur.val > val:
                    cur.next = None
                    t2.next = cur
                    t2 = t2.next
                else:
                    cur.next = None
                    t3.next = cur
                    t3 = t3.next
                cur = tmp
            h1 = quick_sort(h1.next)              #排序好的小于val的
            h2 = quick_sort(h2.next)              #排序好的大于val的
            h3 = h3.next                          #排序好的等于val的
            t3.next = h2                          #等于后面接大于
            if h1 == None:                        #小于为空就不接前面的部分了
                return h3
            else:
                t1 = h1                           #不为空找到尾结点
                while t1.next:
                    t1 = t1.next
                t1.next = h3                      #接到前面
                return h1
        return quick_sort(head)
        

你可能感兴趣的:(hot100,链表,排序算法,算法)