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) 时间复杂度和常数级空间复杂度下,对链表进行排序吗?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func sortList(head *ListNode) *ListNode {
return sort(head, nil)
}

func sort(head, tail *ListNode) *ListNode {
if head == nil {
return head
}
if head.Next == tail {
// tail 放到下一段去排序
head.Next = nil
return head
}

slow, fast := head, head
for fast != tail {
slow = slow.Next
fast = fast.Next
if fast != tail {
fast = fast.Next
}
}
mid := slow
return merge(sort(head, mid), sort(mid, tail))
}

func merge(h1, h2 *ListNode) *ListNode {
dummy := &ListNode{}
t, t1, t2 := dummy, h1, h2
// 注意这里是 for
for t1 != nil && t2 != nil {
if t1.Val <= t2.Val {
t.Next = t1
t1 = t1.Next
} else {
t.Next = t2
t2 = t2.Next
}
// 移动到下一节点
t = t.Next
}
if t1 != nil {
t.Next = t1
} else if t2 != nil {
t.Next = t2
}
return dummy.Next
}