feat: add solutions to lc problem: No.0147 (#4437)

No.0147.Insertion Sort List
This commit is contained in:
Tomato 2025-05-27 09:46:19 +08:00 committed by GitHub
parent 185c94f2ed
commit ce35926195
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 103 additions and 0 deletions

View File

@ -181,6 +181,42 @@ var insertionSortList = function (head) {
};
```
#### Go
```go
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func insertionSortList(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
dummy := &ListNode{head.Val, head}
pre, cur := dummy, head
for cur != nil {
if pre.Val <= cur.Val {
pre = cur
cur = cur.Next
continue
}
p := dummy
for p.Next.Val <= cur.Val {
p = p.Next
}
t := cur.Next
cur.Next = p.Next
p.Next = cur
pre.Next = t
cur = t
}
return dummy.Next
}
```
<!-- tabs:end -->
<!-- solution:end -->

View File

@ -171,6 +171,42 @@ var insertionSortList = function (head) {
};
```
#### Go
```go
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func insertionSortList(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
dummy := &ListNode{head.Val, head}
pre, cur := dummy, head
for cur != nil {
if pre.Val <= cur.Val {
pre = cur
cur = cur.Next
continue
}
p := dummy
for p.Next.Val <= cur.Val {
p = p.Next
}
t := cur.Next
cur.Next = p.Next
p.Next = cur
pre.Next = t
cur = t
}
return dummy.Next
}
```
<!-- tabs:end -->
<!-- solution:end -->

View File

@ -0,0 +1,31 @@
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func insertionSortList(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
dummy := &ListNode{head.Val, head}
pre, cur := dummy, head
for cur != nil {
if pre.Val <= cur.Val {
pre = cur
cur = cur.Next
continue
}
p := dummy
for p.Next.Val <= cur.Val {
p = p.Next
}
t := cur.Next
cur.Next = p.Next
p.Next = cur
pre.Next = t
cur = t
}
return dummy.Next
}