-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsortList.go
More file actions
52 lines (44 loc) · 934 Bytes
/
Copy pathsortList.go
File metadata and controls
52 lines (44 loc) · 934 Bytes
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
/* https://leetcode.com/problems/sort-list/description/
Sort a linked list in O(n log n) time using constant space complexity.
*/
package lll
func sortList(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
// cut List
slow, fast := head, head
var tail *ListNode
for fast != nil && fast.Next != nil {
tail, slow, fast = slow, slow.Next, fast.Next.Next
}
tail.Next = nil
return sortListHelper(sortList(head), sortList(slow))
}
func sortListHelper(left, right *ListNode) (head *ListNode) {
if left == nil {
return right
} else if right == nil {
return left
}
var p, cur *ListNode
for left != nil && right != nil {
if left.Val < right.Val {
cur, left = left, left.Next
} else {
cur, right = right, right.Next
}
if head == nil {
head = cur
} else {
p.Next = cur
}
p = cur
}
if left != nil {
p.Next = left
} else {
p.Next = right
}
return head
}