148. 排序链表
mid
给你链表的头结点 head
,请将其按 升序 排列并返回 排序后的链表 。
自底向上归并
链表的排序真他妈烦啊
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
| func sortList(head *ListNode) *ListNode {
if head == nil {
return nil
}
length := 0
for n := head; n != nil; n = n.Next {
length++
}
fakeHead := &ListNode{Next: head}
for subLen := 1; subLen < length; subLen *= 2 {
prev, cur := fakeHead, fakeHead.Next
for cur != nil {
nodeA := cur
for i := 1; i < subLen && cur.Next != nil; i++ {
cur = cur.Next
}
nodeB := cur.Next
cur.Next = nil // 斩断nodeA
cur = nodeB
for i := 1; i < subLen && cur != nil; i++ {
cur = cur.Next
}
var nextNode *ListNode
if cur != nil {
nextNode = cur.Next
cur.Next = nil // 斩断nodeB
}
prev.Next = merge(nodeA, nodeB)
for prev.Next != nil {
prev = prev.Next
}
cur = nextNode
}
}
return fakeHead.Next
}
func merge(a, b *ListNode) *ListNode {
fakeHead := &ListNode{}
p:=fakeHead
for {
if a == nil && b == nil {
break
} else if a == nil {
p.Next = b
b=b.Next
} else if b == nil {
p.Next = a
a=a.Next
} else {
if a.Val > b.Val {
p.Next = b
b = b.Next
} else {
p.Next = a
a = a.Next
}
}
p=p.Next
}
return fakeHead.Next
}
|