目录

0148:排序链表(★)

力扣第 148 题

题目

给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表

示例 1:

输入:head = [4,2,1,3]
输出:[1,2,3,4]

示例 2:

输入:head = [-1,5,3,4,0]
输出:[-1,0,3,4,5]

示例 3:

输入:head = []
输出:[]

提示:

  • 链表中节点的数目在范围 [0, 5 * 104]
  • -105 <= Node.val <= 105

进阶:你可以在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序吗?

分析

  • 要求 O(n log n) 时间复杂度和常数级空间复杂度,想到归并排序
  • 用快慢指针找到中点,归并部分即问题 0021

解答

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution:
    def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        def merge(a, b):
            dum=p=ListNode()
            while a and b:
                if a.val<=b.val:
                    p.next = a
                    a = a.next
                else:
                    p.next = b
                    b = b.next
                p = p.next
            p.next = a or b
            return dum.next
        
        if not head or not head.next:
            return head
        slow=fast=head
        while fast.next and fast.next.next:
            slow,fast = slow.next,fast.next.next
        a, b = head, slow.next
        slow.next = None
        return merge(self.sortList(a), self.sortList(b))

283 ms