更新 problem 147

This commit is contained in:
YDZ
2019-03-22 17:23:33 +08:00
parent 9be57dc6f0
commit ed459e3bb2
3 changed files with 119 additions and 0 deletions

View File

@ -0,0 +1,29 @@
package leetcode
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func insertionSortList(head *ListNode) *ListNode {
if head == nil {
return head
}
newHead := &ListNode{Val: 0, Next: nil} // 这里初始化不要直接指向 head为了下面循环可以统一处理
cur := head
pre := newHead
next := &ListNode{Val: 0, Next: nil}
for cur != nil {
next = cur.Next
for pre.Next != nil && pre.Next.Val < cur.Val {
pre = pre.Next
}
cur.Next = pre.Next
pre.Next = cur
pre = newHead // 归位,重头开始
cur = next
}
return newHead.Next
}

View File

@ -0,0 +1,56 @@
package leetcode
import (
"fmt"
"testing"
)
type question147 struct {
para147
ans147
}
// para 是参数
// one 代表第一个参数
type para147 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans147 struct {
one []int
}
func Test_Problem147(t *testing.T) {
qs := []question147{
question147{
para147{[]int{4, 2, 1, 3}},
ans147{[]int{1, 2, 3, 4}},
},
question147{
para147{[]int{1}},
ans147{[]int{1}},
},
question147{
para147{[]int{-1, 5, 3, 4, 0}},
ans147{[]int{-1, 0, 3, 4, 5}},
},
question147{
para147{[]int{}},
ans147{[]int{}},
},
}
fmt.Printf("------------------------Leetcode Problem 147------------------------\n")
for _, q := range qs {
_, p := q.ans147, q.para147
fmt.Printf("【input】:%v 【output】:%v\n", p, L2s(insertionSortList(S2l(p.one))))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,34 @@
# [147. Insertion Sort List](https://leetcode.com/problems/insertion-sort-list/)
## 题目
Sort a linked list using insertion sort.
A graphical example of insertion sort. The partial sorted list (black) initially contains only the first element in the list.
With each iteration one element (red) is removed from the input data and inserted in-place into the sorted list
Algorithm of Insertion Sort:
Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list.
At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there.
It repeats until no input elements remain.
Example 1:
```c
Input: 4->2->1->3
Output: 1->2->3->4
```
Example 2:
```c
Input: -1->5->3->4->0
Output: -1->0->3->4->5
```
## 题目大意
链表的插入排序