zoukankan      html  css  js  c++  java
  • 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
    
  • 相关阅读:
    mac 显示隐藏文件 快捷键
    Swift常用内置函数介绍
    MacOS Catalina 虚拟机VMware Fusion 重装教程 和问题
    swift 时间显示格式
    mybatis自测错题总结
    Spring核心概念和案例
    MyBatis注解
    MyBatis缓存
    关联查询
    智能标签
  • 原文地址:https://www.cnblogs.com/panweiwei/p/12900119.html
Copyright © 2011-2022 走看看