Skip to content

Commit 4959dba

Browse files
committed
sort_list
1 parent 30f5f7d commit 4959dba

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t
131131
#### [145. binary tree postorder traversal](https://github.com/hitzzc/go-leetcode/tree/master/binary_tree_postorder_traversal)
132132
#### [146. LRU Cache](https://github.com/hitzzc/go-leetcode/tree/master/lru_cache)
133133
#### [147. insertion sort list](https://github.com/hitzzc/go-leetcode/tree/master/insertion_sort_list)
134+
#### [148. sort list](https://github.com/hitzzc/go-leetcode/tree/master/sort_list)
134135

135136

136137

sort_list/sort_list.go

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package sort_list
2+
3+
type ListNode struct {
4+
Val int
5+
Next *ListNode
6+
}
7+
8+
func sortList(head *ListNode) *ListNode {
9+
if head == nil || head.Next == nil {
10+
return head
11+
}
12+
secHead := split(head)
13+
return merge(sortList(head), sortList(secHead))
14+
}
15+
16+
func split(head *ListNode) *ListNode {
17+
if head == nil || head.Next == nil {
18+
return nil
19+
}
20+
slow, fast := head, head
21+
var tail *ListNode
22+
for fast != nil && fast.Next != nil {
23+
tail = slow
24+
slow = slow.Next
25+
fast = fast.Next.Next
26+
}
27+
tail.Next = nil
28+
return slow
29+
}
30+
31+
func merge(left, right *ListNode) (head *ListNode) {
32+
if left == nil {
33+
return right
34+
} else if right == nil {
35+
return left
36+
}
37+
var p, cur *ListNode
38+
for left != nil && right != nil {
39+
if left.Val < right.Val {
40+
cur = left
41+
left = left.Next
42+
} else {
43+
cur = right
44+
right = right.Next
45+
}
46+
if head == nil {
47+
head = cur
48+
} else {
49+
p.Next = cur
50+
}
51+
p = cur
52+
}
53+
if left != nil {
54+
p.Next = left
55+
} else {
56+
p.Next = right
57+
}
58+
return head
59+
}

0 commit comments

Comments
 (0)