Skip to content
This repository was archived by the owner on Sep 20, 2023. It is now read-only.

Commit e962df6

Browse files
aQuaaQua
aQua
authored and
aQua
committed
147 accepted. 159ms > 9ms
1 parent 050068c commit e962df6

File tree

3 files changed

+92
-0
lines changed

3 files changed

+92
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
# [147. Insertion Sort List](https://leetcode.com/problems/insertion-sort-list/)
2+
3+
## 题目
4+
Sort a linked list using insertion sort.
5+
6+
## 解题思路
7+
8+
见程序注释
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package Problem0147
2+
3+
import (
4+
"github.com/aQuaYi/LeetCode-in-Golang/kit"
5+
)
6+
7+
type ListNode = kit.ListNode
8+
9+
func insertionSortList(head *ListNode) *ListNode {
10+
if head == nil || head.Next == nil {
11+
return head
12+
}
13+
14+
count := 0
15+
temp := &ListNode{Next: head}
16+
for temp.Next != nil {
17+
count++
18+
temp = temp.Next
19+
}
20+
21+
headPre := &ListNode{Next: head}
22+
23+
for cnt := count - 1; cnt > 0; cnt-- {
24+
temp = headPre
25+
for c := cnt; c > 0; c-- {
26+
if temp.Next.Val > temp.Next.Next.Val {
27+
tempNext := temp.Next
28+
temp.Next = temp.Next.Next
29+
tempNext.Next = temp.Next.Next
30+
temp.Next.Next = tempNext
31+
}
32+
temp = temp.Next
33+
}
34+
}
35+
36+
return headPre.Next
37+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package Problem0147
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
7+
"github.com/aQuaYi/LeetCode-in-Golang/kit"
8+
9+
"github.com/stretchr/testify/assert"
10+
)
11+
12+
// tcs is testcase slice
13+
var tcs = []struct {
14+
head []int
15+
ans []int
16+
}{
17+
18+
{
19+
[]int{2, 4, 3, 1, 5},
20+
[]int{1, 2, 3, 4, 5},
21+
},
22+
23+
// 可以有多个 testcase
24+
}
25+
26+
func Test_insertionSortList(t *testing.T) {
27+
ast := assert.New(t)
28+
29+
for _, tc := range tcs {
30+
fmt.Printf("~~%v~~\n", tc)
31+
32+
head := kit.Ints2List(tc.head)
33+
ast.Equal(tc.ans, kit.List2Ints(insertionSortList(head)), "输入:%v", tc)
34+
}
35+
}
36+
37+
func Benchmark_insertionSortList(b *testing.B) {
38+
head := &ListNode{}
39+
for i := 0; i < b.N; i++ {
40+
for _, tc := range tcs {
41+
b.StopTimer()
42+
head = kit.Ints2List(tc.head)
43+
b.StartTimer()
44+
insertionSortList(head)
45+
}
46+
}
47+
}

0 commit comments

Comments
 (0)