# 109. 排序链表

### 题意

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

### 实现

# Definition for singly-linked list.# class ListNode(object):#     def __init__(self, x):#         self.val = x#         self.next = None​class Solution(object):    def sortList(self, head):        """        :type head: ListNode        :rtype: ListNode        """        if not head:            return None      # 转化为数组        result = []        head_tmp = head        while head_tmp:            result.append(head_tmp.val)            head_tmp = head_tmp.next                # 归并排序        result = self.merge_sort(result)        # 将排序后的结果重新填充到链表中        head_tmp = head        for i in range(len(result)):            head_tmp.val = result[i]            head_tmp = head_tmp.next                return head            def merge(self, left, right):        i, j = 0, 0        left_len, right_len = len(left), len(right)        result = []        while i < left_len and j < right_len:            if left[i] < right[j]:                result.append(left[i])                i += 1            else:                result.append(right[j])                j += 1        result += left[i:]        result += right[j:]        return result​    def merge_sort(self, lists):        lists_len = len(lists)        if lists_len <= 1:            return lists​        center = lists_len / 2        left = self.merge_sort(lists[:center])        right = self.merge_sort(lists[center:])        return self.merge(left, right)

posted @ 2019-03-16 14:52  banananana  阅读(65)  评论(0编辑  收藏