leetcode(52)-排序链表

在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。

示例 1:

输入: 4->2->1->3
输出: 1->2->3->4
示例 2:

输入: -1->5->3->4->0
输出: -1->0->3->4->5

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sort-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

from collections import defaultdict
class Solution:
    def sortList(self, head: ListNode) -> ListNode:
        if head is None:return None
        maps = defaultdict(lambda:0)
        t =  head
        maps[head.val]+=1
        while t.next is not None:
            maps[t.next.val]+=1
            if maps[t.next.val]>1:
                t.next = t.next.next
            else:
                t = t.next
       
       
        def sort(head):  
            #print('====')
            if head is None:return None
            index = head
            right_head = ListNode()
            right_index = right_head
            left_head = ListNode()
            left_index = left_head
            while index.next is not None:
                index = index.next
                if index.val <= head.val:
                    left_index.next = index
                    left_index = left_index.next
                else:
                    right_index.next = index
                    right_index = right_index.next
            right_index.next = None
            left_index.next = None
            if right_head.next is not None:
                right_head,tail1 = sort(right_head.next)
                head.next = right_head
            else:
                tail1 = head
            if left_head.next is not None:
                left_head,tail2 = sort(left_head.next)
                tail2.next = head
            else:
                left_head = head
            tail1.next = None
            return left_head, tail1
        head,_ = sort(head)
        index = head
       
        while index is not None:
            if maps[index.val]>1:
                tmp = index.next
                ln = maps[index.val]
                for i in range(1,ln):
                    node = ListNode(index.val)
                    index.next = node
                    index = index.next
                index.next = tmp
            index = index.next
        return head
posted @ 2020-10-06 20:43  木子士心王大可  阅读(58)  评论(0)    收藏  举报