File tree Expand file tree Collapse file tree 2 files changed +80
-1
lines changed
linkedlist_array/148.排序链表 Expand file tree Collapse file tree 2 files changed +80
-1
lines changed Original file line number Diff line number Diff line change @@ -82,4 +82,5 @@ $ 现在开始,分Tag笔记做过的题
82
82
92 |https://leetcode-cn.com/problems/reverse-linked-list-ii/ | [ 反转链表 II] ( ./linkedlist_array/92.反转链表II )
83
83
141 |https://leetcode-cn.com/problems/linked-list-cycle/ | [ 环形链表] ( ./linkedlist_array/141.环形链表 )
84
84
142 |https://leetcode-cn.com/problems/linked-list-cycle-ii/ | [ 环形链表 II] ( ./linkedlist_array/142.环形链表II )
85
- 143 |https://leetcode-cn.com/problems/reorder-list/ | [ 重排链表] ( ./linkedlist_array/143.重排链表 )
85
+ 143 |https://leetcode-cn.com/problems/reorder-list/ | [ 重排链表] ( ./linkedlist_array/143.重排链表 )
86
+ 148 |https://leetcode-cn.com/problems/sort-list/ | [ 排序链表] ( ./linkedlist_array/148.排序链表 )
Original file line number Diff line number Diff line change
1
+ # 148. 排序链表
2
+ 在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
3
+
4
+ 示例 1:
5
+ ```
6
+ 输入: 4->2->1->3
7
+ 输出: 1->2->3->4
8
+ ```
9
+ 示例 2:
10
+ ```
11
+ 输入: -1->5->3->4->0
12
+ 输出: -1->0->3->4->5
13
+ ```
14
+ ``` go
15
+ func sortList (head *ListNode ) *ListNode {
16
+ }
17
+ ```
18
+
19
+ ## 解题思路
20
+ 二分法
21
+
22
+ ## 题解
23
+
24
+ ``` go
25
+ func sortList (head *ListNode ) *ListNode {
26
+ if head == nil || head.Next == nil {
27
+ return head
28
+ }
29
+ mid := findMid (head)
30
+ right := sortList (mid.Next )
31
+ mid.Next = nil
32
+
33
+ left := sortList (head)
34
+
35
+ return merge (left , right)
36
+
37
+ }
38
+
39
+ func merge (list1 , list2 *ListNode ) *ListNode {
40
+
41
+ dummy := &ListNode{}
42
+ tail := dummy
43
+
44
+ for list1 != nil && list2 != nil {
45
+ if list1.Val > list2.Val {
46
+ tail.Next = list2
47
+ list2 = list2.Next
48
+ } else {
49
+ tail.Next = list1
50
+ list1 = list1.Next
51
+ }
52
+ tail = tail.Next
53
+ }
54
+
55
+ if list1 != nil {
56
+ tail.Next = list1
57
+ }
58
+
59
+ if list2 != nil {
60
+ tail.Next = list2
61
+ }
62
+
63
+ return dummy.Next
64
+
65
+ }
66
+
67
+ func findMid (head *ListNode ) *ListNode {
68
+ slow := head
69
+ fast := head.Next
70
+
71
+ for fast != nil && fast.Next != nil {
72
+ slow = slow.Next
73
+ fast = fast.Next .Next
74
+ }
75
+ return slow
76
+ }
77
+
78
+ ```
You can’t perform that action at this time.
0 commit comments