-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsort-list.go
77 lines (70 loc) · 1.55 KB
/
sort-list.go
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package list
// https://leetcode-cn.com/problems/sort-list/
// Merge sort from top to down
// Time: O(nlogn)
// Space: O(logn) by call stack
// TOP -> DOWN
// 3 -> 2 -> 5 -> 1
// |
// 2 -> 3 1 -> 5
// |
// 1 -> 2 -> 3 -> 5
// recursively
func sortList(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
dummy := &ListNode{Next: head}
slow, fast := dummy, dummy
for fast != nil && fast.Next != nil {
slow = slow.Next
fast = fast.Next.Next
}
left, right := head, slow.Next
slow.Next = nil
left, right = sortList(left), sortList(right)
return mergeTwoLists(left, right)
}
// Merge from down to top.
// Time: O(nlogn)
// Space: O(1)
func sortListII(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
// n is the length of list
n, p := 0, head
for p != nil {
n++
p = p.Next
}
dummy := &ListNode{Next: head}
for step := 1; step <= n; step *= 2 {
prev, curr := dummy, dummy
for curr != nil { // every sub-list
leftHead := prev.Next
rightHead := split(prev.Next, step)
curr = split(rightHead, step)
prev.Next = mergeTwoLists(leftHead, rightHead)
for prev.Next != nil {
prev = prev.Next
}
prev.Next = curr
}
}
return dummy.Next
}
// return right head of split list, the left tail pointer to null.
func split(head *ListNode, step int) *ListNode {
if head == nil {
return nil
}
dummy := &ListNode{Next: head}
curr := dummy
for i := 0; i < step && curr.Next != nil; i++ {
curr = curr.Next
}
right := curr.Next
curr.Next = nil
return right
}