leetcode 148 python 排序链表

传送门

题目要求

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

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

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

思路

使用归并思想,用快慢指针找到链表中间节点,分成左右两段,再分,再分....,对左右2段进行排序,递归。

# 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 or not head.next:
            return head
        cut = slow = fast = head
        while fast and fast.next:
            cut = slow
            fast = fast.next.next
            slow = slow.next
        cut.next = None
        left = self.sortList(head)
        right = self.sortList(slow)
        return self.merge(left, right)
    
    def merge(self, left, right):
        m = n = ListNode(0)
        while left and right:
            if left.val <= right.val:
                n.next = left
                left = left.next
            else:
                n.next = right
                right = right.next
            n = n.next
        n.next = left or right
        return m.next

你可能感兴趣的:(leetcode 148 python 排序链表)