148. 排序链表

时间:2020-05-16
本文章向大家介绍148. 排序链表,主要包括148. 排序链表使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。



方法一:快排

详细参考:https://www.cnblogs.com/panweiwei/p/12897773.html

class Solution(object):
    def sortList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        def partition(start, end):
            node = start.next.next
            pivotPrev = start.next
            pivotPrev.next = end
            pivotPost = pivotPrev
            while node != end:
                temp = node.next
                if node.val > pivotPrev.val:
                    node.next = pivotPost.next
                    pivotPost.next = node
                elif node.val < pivotPrev.val:
                    node.next = start.next
                    start.next = node
                else:
                    node.next = pivotPost.next
                    pivotPost.next = node
                    pivotPost = pivotPost.next
                node = temp
            return [pivotPrev, pivotPost]

        def quicksort(start, end):
            if start.next != end:
                prev, post = partition(start, end)
                quicksort(start, prev)
                quicksort(post, end)

        ans = ListNode(0)
        ans.next = head
        quicksort(ans, None)
        return ans.next

方法二:归并排序

详细参考:https://www.cnblogs.com/panweiwei/p/12898022.html

class Solution(object):
    def sortList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head or not head.next:
            return head
        # 用快慢指针找链表中间节点,循环结束时:slow.next指向中间节点。
        slow, fast = head, head
        while fast.next and fast.next.next:
            slow = slow.next
            fast = fast.next.next
        # 对右半部分归并排序
        right = self.sortList(slow.next)
        # 断开左右两部分链表
        slow.next = None
        # 对左半部分归并排序
        left = self.sortList(head)
        return self.mergeLink(left, right)

    # 合并两个链表:按升序
    def mergeLink(self, left, right):
        node = ListNode(-1)
        head = node
        while left and right:
            if left.val < right.val:
                node.next = left
                left = left.next
            else:
                node.next = right
                right = right.next
            node = node.next
        node.next = left if left else right
        return head.next

原文地址:https://www.cnblogs.com/panweiwei/p/12900119.html