Skip to content

Commit e152fb8

Browse files
committed
feat: add solutions to lc problem: No.0147
No.0147.Insertion Sort List
1 parent b2a6267 commit e152fb8

File tree

3 files changed

+103
-0
lines changed

3 files changed

+103
-0
lines changed

solution/0100-0199/0147.Insertion Sort List/README.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,42 @@ var insertionSortList = function (head) {
181181
};
182182
```
183183

184+
#### Go
185+
186+
```go
187+
/**
188+
* Definition for singly-linked list.
189+
* type ListNode struct {
190+
* Val int
191+
* Next *ListNode
192+
* }
193+
*/
194+
func insertionSortList(head *ListNode) *ListNode {
195+
if head == nil || head.Next == nil {
196+
return head
197+
}
198+
dummy := &ListNode{head.Val, head}
199+
pre, cur := dummy, head
200+
for cur != nil {
201+
if pre.Val <= cur.Val {
202+
pre = cur
203+
cur = cur.Next
204+
continue
205+
}
206+
p := dummy
207+
for p.Next.Val <= cur.Val {
208+
p = p.Next
209+
}
210+
t := cur.Next
211+
cur.Next = p.Next
212+
p.Next = cur
213+
pre.Next = t
214+
cur = t
215+
}
216+
return dummy.Next
217+
}
218+
```
219+
184220
<!-- tabs:end -->
185221

186222
<!-- solution:end -->

solution/0100-0199/0147.Insertion Sort List/README_EN.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,42 @@ var insertionSortList = function (head) {
171171
};
172172
```
173173

174+
#### Go
175+
176+
```go
177+
/**
178+
* Definition for singly-linked list.
179+
* type ListNode struct {
180+
* Val int
181+
* Next *ListNode
182+
* }
183+
*/
184+
func insertionSortList(head *ListNode) *ListNode {
185+
if head == nil || head.Next == nil {
186+
return head
187+
}
188+
dummy := &ListNode{head.Val, head}
189+
pre, cur := dummy, head
190+
for cur != nil {
191+
if pre.Val <= cur.Val {
192+
pre = cur
193+
cur = cur.Next
194+
continue
195+
}
196+
p := dummy
197+
for p.Next.Val <= cur.Val {
198+
p = p.Next
199+
}
200+
t := cur.Next
201+
cur.Next = p.Next
202+
p.Next = cur
203+
pre.Next = t
204+
cur = t
205+
}
206+
return dummy.Next
207+
}
208+
```
209+
174210
<!-- tabs:end -->
175211

176212
<!-- solution:end -->
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* type ListNode struct {
4+
* Val int
5+
* Next *ListNode
6+
* }
7+
*/
8+
func insertionSortList(head *ListNode) *ListNode {
9+
if head == nil || head.Next == nil {
10+
return head
11+
}
12+
dummy := &ListNode{head.Val, head}
13+
pre, cur := dummy, head
14+
for cur != nil {
15+
if pre.Val <= cur.Val {
16+
pre = cur
17+
cur = cur.Next
18+
continue
19+
}
20+
p := dummy
21+
for p.Next.Val <= cur.Val {
22+
p = p.Next
23+
}
24+
t := cur.Next
25+
cur.Next = p.Next
26+
p.Next = cur
27+
pre.Next = t
28+
cur = t
29+
}
30+
return dummy.Next
31+
}

0 commit comments

Comments
 (0)