feat(Go-Tool):2020/12/7 :添加container包使用示例和源码分析

This commit is contained in:
Huangzj
2020-12-07 15:00:24 +08:00
parent 55d6488fc3
commit 23d7d6e226
8 changed files with 845 additions and 0 deletions
+157
View File
@@ -0,0 +1,157 @@
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package heap provides heap operations for any type that implements
// heap.Interface. A heap is a tree with the property that each node is the
// minimum-valued node in its subtree.
//
// The minimum element in the tree is the root, at index 0.
//
// A heap is a common way to implement a priority queue. To build a priority
// queue, implement the Heap interface with the (negative) priority as the
// ordering for the Less method, so Push adds items while Pop removes the
// highest-priority item from the queue. The Examples include such an
// implementation; the file example_pq_test.go has the complete source.
//
//read note 拷贝一个代码过来解析.感觉在go里面拷贝代码简单多了,依赖可以直接使用。我在这边使用read note(自定义todo标识)来标识我的解析.
package SourceAnalysis
import "sort"
// The Interface type describes the requirements
// for a type using the routines in this package.
// Any type that implements it may be used as a
// min-heap with the following invariants (established after
// Init has been called or if the data is empty or sorted):
//
// !h.Less(j, i) for 0 <= i < h.Len() and 2*i+1 <= j <= 2*i+2 and j < h.Len()
//
// Note that Push and Pop in this interface are for package heap's
// implementation to call. To add and remove things from the heap,
// use heap.Push and heap.Pop.
type Interface interface {
sort.Interface
Push(x interface{}) // add x as element Len()
Pop() interface{} // remove and return element Len() - 1.
}
// Init establishes the heap invariants required by the other routines in this package.
// Init is idempotent with respect to the heap invariants
// and may be called whenever the heap invariants may have been invalidated.
// The complexity is O(n) where n = h.Len().
//read note 对整个Interface 进行重构,时间复杂度是 O(n)
func Init(h Interface) {
// heapify
n := h.Len()
//read note 从最小父节点,到第0位的根节点,分别向下进行重构处理(之所以要用循环是因为一次向下的重构,只能对一条连续的分支进行重构,不彻底.)
for i := n/2 - 1; i >= 0; i-- {
down(h, i, n)
}
}
// Push pushes the element x onto the heap.
// The complexity is O(log n) where n = h.Len().
// read note 这个Push方法是往 Interface里面去新增一个元素.和我们继承的Push方法有差别.这边同时候做了重构操作.
// 一次Push的时间复杂度是 O(logN),一次Init的时间复杂度是O(N),按道理Push的元素越多,Init的效率越高
func Push(h Interface, x interface{}) {
//read note 先把元素添加进去
h.Push(x)
//read note 然后在从下往上进行重构处理,正常情况下Push都是把元素添加在最后一个位置,如果实现的方法,把Push添加到其他位置如果不进行Init,应该是会有问题.
up(h, h.Len()-1)
}
// Pop removes and returns the minimum element (according to Less) from the heap.
// The complexity is O(log n) where n = h.Len().
// Pop is equivalent to Remove(h, 0).
//read note 把最小的元素输出,需要注意的是真正的Pop必须是调用这个方法,而不是我们继承的那个方法.
// 时间复杂度是O(logN)
func Pop(h Interface) interface{} {
//read note 真正的Pop输出的是最小的元素,也就是最小堆的第0位置的元素
// 所以这边的操作是把第0位的数组放到最后一位,然后从位置0开始,到N-1的位置,对所有元素进行down(父子节点比较交换)的操作
n := h.Len() - 1
h.Swap(0, n)
down(h, 0, n)
return h.Pop()
}
// Remove removes and returns the element at index i from the heap.
// The complexity is O(log n) where n = h.Len().
//read note 移除某个位置的元素,时间复杂度是 o(logn)
func Remove(h Interface, i int) interface{} {
//read note 判断移除的下标不等于最后一个元素位置,要特殊处理
n := h.Len() - 1
if n != i {
//read note 交换第i个元素和最后一个元素
h.Swap(i, n)
//read note Fix的处理操作,这边只会处理到移除一个元素后的位置,也就是说被移除的那个元素(在最后的位置)不会参与重构数组的操作
if !down(h, i, n) {
up(h, i)
}
}
//read note 调用Pop,把最后一个元素返回回去
return h.Pop()
}
// Fix re-establishes the heap ordering after the element at index i has changed its value.
// Changing the value of the element at index i and then calling Fix is equivalent to,
// but less expensive than, calling Remove(h, i) followed by a Push of the new value.
// The complexity is O(log n) where n = h.Len().
//read note 当下标为i的元素发生改变,需要进行一次Fix的处理,时间复杂度是 o(logn)
func Fix(h Interface, i int) {
//read note 想从下标i的这个元素往下查找处理,如果往下没有交换元素,再往上进行处理.
if !down(h, i, h.Len()) {
up(h, i)
}
}
//read note h: 对应的数组数据
//read note j:子节点的下标
//read note 方法作用
func up(h Interface, j int) {
for {
//read note 拿到对应的父节点的下标
i := (j - 1) / 2 // parent
//read note 找到最后一个父节点 || 父节点比子节点小,则跳出循环
if i == j || !h.Less(j, i) {
break
}
//read note 否则就是父节点比子节点的值大,需要交换对应的元素,然后找到父节点的下标,再往上找其父节点的关系
h.Swap(i, j)
j = i
}
}
//read note h: 对应的数组数据
//read note i0: 需要下发处理的坐标,这边也就是左右子节点的父节点下标.
//read note n: 数组对应的总长度
//read note 方法作用:从父节点开始,循环向下判断对应的元素是否在对应的环境上
func down(h Interface, i0, n int) bool {
//read note 把父节点的下标拿出来
i := i0
//read note 循环的结束条件是:
for {
//read note 找到左边子节点下标
j1 := 2*i + 1
//read note 退出条件1:超过最大长度或者是负值(这个应该是针对传入就有问题的处理)
if j1 >= n || j1 < 0 { // j1 < 0 after int overflow
break
}
//read note 拿到左孩子和右孩子中比较小的那个元素(的下标)
j := j1 // left child
if j2 := j1 + 1; j2 < n && h.Less(j2, j1) {
j = j2 // = 2*i + 2 // right child
}
//read note 判断父节点和子节点的大小关系,小的元素应该在父节点,所以如果子节点本身就比较小,直接退出循环,否则交换元素
//read note 然后再把下标移动到被交换的这个元素上,计算被交换的这个元素和它的左右子节点的大小关系,进入下一个循环
if !h.Less(j, i) {
break
}
h.Swap(i, j)
i = j
}
//read note 判断是否发生了交换操作
return i > i0
}
+255
View File
@@ -0,0 +1,255 @@
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package list implements a doubly linked list.
//
// To iterate over a list (where l is a *List):
// for e := l.Front(); e != nil; e = e.Next() {
// // do something with e.Value
// }
//
package SourceAnalysis
// Element is an element of a linked list.
//read note list中对应的元素,list相当是通过一个链表来链接所有的Element元素.
type Element struct {
// Next and previous pointers in the doubly-linked list of elements.
// To simplify the implementation, internally a list l is implemented
// as a ring, such that &l.root is both the next element of the last
// list element (l.Back()) and the previous element of the first list
// element (l.Front()).
//read note 指向下一个和前一个元素的指针.internally a list l is implemented as a ring:内部实现实际是一个环
next, prev *Element
// The list to which this element belongs.
//read note 链表头,这边是设置表头为哨兵的模式进行链表的处理的
list *List
// The value stored with this element.
//read note Element中实际的元素值
Value interface{}
}
// Next returns the next list element or nil.
func (e *Element) Next() *Element {
//read note 获取下一个元素,这边判断条件包含 list不为空,以及next不为链表头结点(哨兵).
if p := e.next; e.list != nil && p != &e.list.root {
return p
}
return nil
}
// Prev returns the previous list element or nil.
func (e *Element) Prev() *Element {
//read note 与Next一样的道理,判断list不为空,以及pre不等于链表头结点
if p := e.prev; e.list != nil && p != &e.list.root {
return p
}
return nil
}
// List represents a doubly linked list.
// The zero value for List is an empty list ready to use.
//read note 设置哨兵的链表实现
type List struct {
//read note 哨兵结点
root Element // sentinel list element, only &root, root.prev, and root.next are used
//read note 链表长度
len int // current list length excluding (this) sentinel element
}
// Init initializes or clears list l.
func (l *List) Init() *List {
//read note 初始化的时候,链表的哨兵结点pre和next是互相指向的,这也可以作为判断链表是否为空的依据
l.root.next = &l.root
l.root.prev = &l.root
l.len = 0
return l
}
// New returns an initialized list.
func New() *List { return new(List).Init() }
// Len returns the number of elements of list l.
// The complexity is O(1).
func (l *List) Len() int { return l.len }
// Front returns the first element of list l or nil if the list is empty.
// read note 返回第一个元素,如果链表不为空,则返回哨兵结点的next就是一个链表结点
func (l *List) Front() *Element {
if l.len == 0 {
return nil
}
return l.root.next
}
// Back returns the last element of list l or nil if the list is empty.
// read note 所以list是一个环,如果链表不为空,则最后一个元素可以通过哨兵的prev来获取到.
func (l *List) Back() *Element {
if l.len == 0 {
return nil
}
return l.root.prev
}
// lazyInit lazily initializes a zero List value.
func (l *List) lazyInit() {
if l.root.next == nil {
l.Init()
}
}
// insert inserts e after at, increments l.len, and returns e.
//read note 在某一个位置后面加入一个element,只需要设置一下长度,前后链表地址的指向即可。
func (l *List) insert(e, at *Element) *Element {
n := at.next
at.next = e
e.prev = at
e.next = n
n.prev = e
e.list = l
l.len++
return e
}
// insertValue is a convenience wrapper for insert(&Element{Value: v}, at).
func (l *List) insertValue(v interface{}, at *Element) *Element {
return l.insert(&Element{Value: v}, at)
}
// remove removes e from its list, decrements l.len, and returns e.
//read note 移除某个元素,返回该元素并设置不相关的属性为空,防止内存泄露.
func (l *List) remove(e *Element) *Element {
e.prev.next = e.next
e.next.prev = e.prev
e.next = nil // avoid memory leaks
e.prev = nil // avoid memory leaks
e.list = nil
l.len--
return e
}
// move moves e to next to at and returns e.
//read note 移动某个元素,本质上和插入某个元素有点类似.即移除对应节点后,再在对应的节点后面插入该元素
func (l *List) move(e, at *Element) *Element {
if e == at {
return e
}
e.prev.next = e.next
e.next.prev = e.prev
n := at.next
at.next = e
e.prev = at
e.next = n
n.prev = e
return e
}
// Remove removes e from l if e is an element of list l.
// It returns the element value e.Value.
// The element must not be nil.
func (l *List) Remove(e *Element) interface{} {
if e.list == l {
// if e.list == l, l must have been initialized when e was inserted
// in l or l == nil (e is a zero Element) and l.remove will crash
l.remove(e)
}
return e.Value
}
// PushFront inserts a new element e with value v at the front of list l and returns e.
func (l *List) PushFront(v interface{}) *Element {
l.lazyInit()
return l.insertValue(v, &l.root)
}
// PushBack inserts a new element e with value v at the back of list l and returns e.
func (l *List) PushBack(v interface{}) *Element {
l.lazyInit()
return l.insertValue(v, l.root.prev)
}
// InsertBefore inserts a new element e with value v immediately before mark and returns e.
// If mark is not an element of l, the list is not modified.
// The mark must not be nil.
func (l *List) InsertBefore(v interface{}, mark *Element) *Element {
if mark.list != l {
return nil
}
// see comment in List.Remove about initialization of l
return l.insertValue(v, mark.prev)
}
// InsertAfter inserts a new element e with value v immediately after mark and returns e.
// If mark is not an element of l, the list is not modified.
// The mark must not be nil.
func (l *List) InsertAfter(v interface{}, mark *Element) *Element {
if mark.list != l {
return nil
}
// see comment in List.Remove about initialization of l
return l.insertValue(v, mark)
}
// MoveToFront moves element e to the front of list l.
// If e is not an element of l, the list is not modified.
// The element must not be nil.
func (l *List) MoveToFront(e *Element) {
if e.list != l || l.root.next == e {
return
}
// see comment in List.Remove about initialization of l
l.move(e, &l.root)
}
// MoveToBack moves element e to the back of list l.
// If e is not an element of l, the list is not modified.
// The element must not be nil.
func (l *List) MoveToBack(e *Element) {
if e.list != l || l.root.prev == e {
return
}
// see comment in List.Remove about initialization of l
l.move(e, l.root.prev)
}
// MoveBefore moves element e to its new position before mark.
// If e or mark is not an element of l, or e == mark, the list is not modified.
// The element and mark must not be nil.
func (l *List) MoveBefore(e, mark *Element) {
if e.list != l || e == mark || mark.list != l {
return
}
l.move(e, mark.prev)
}
// MoveAfter moves element e to its new position after mark.
// If e or mark is not an element of l, or e == mark, the list is not modified.
// The element and mark must not be nil.
func (l *List) MoveAfter(e, mark *Element) {
if e.list != l || e == mark || mark.list != l {
return
}
l.move(e, mark)
}
// PushBackList inserts a copy of an other list at the back of list l.
// The lists l and other may be the same. They must not be nil.
func (l *List) PushBackList(other *List) {
l.lazyInit()
for i, e := other.Len(), other.Front(); i > 0; i, e = i-1, e.Next() {
l.insertValue(e.Value, l.root.prev)
}
}
// PushFrontList inserts a copy of an other list at the front of list l.
// The lists l and other may be the same. They must not be nil.
func (l *List) PushFrontList(other *List) {
l.lazyInit()
for i, e := other.Len(), other.Back(); i > 0; i, e = i-1, e.Prev() {
l.insertValue(e.Value, &l.root)
}
}
+150
View File
@@ -0,0 +1,150 @@
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package ring implements operations on circular lists.
package SourceAnalysis
// A Ring is an element of a circular list, or ring.
// Rings do not have a beginning or end; a pointer to any ring element
// serves as reference to the entire ring. Empty rings are represented
// as nil Ring pointers. The zero value for a Ring is a one-element
// ring with a nil Value.
//
//read note 环结构:指针可能指向任意元素,空链表只有一个nil元素
type Ring struct {
next, prev *Ring
Value interface{} // for use by client; untouched by this library
}
//read note 初始化只是做了指针指向,不会增加环的值
func (r *Ring) init() *Ring {
r.next = r
r.prev = r
return r
}
// Next returns the next ring element. r must not be empty.
//read note:环的下一个值,如果环的next为空,则初始化该环
func (r *Ring) Next() *Ring {
if r.next == nil {
return r.init()
}
return r.next
}
// Prev returns the previous ring element. r must not be empty.
func (r *Ring) Prev() *Ring {
if r.next == nil {
return r.init()
}
return r.prev
}
// Move moves n % r.Len() elements backward (n < 0) or forward (n >= 0)
// in the ring and returns that ring element. r must not be empty.
//
//read note 对环上的当前元素进行n次位置的移动,小于0则向后移动,大于0则向前移动
func (r *Ring) Move(n int) *Ring {
if r.next == nil {
return r.init()
}
switch {
case n < 0:
for ; n < 0; n++ {
r = r.prev
}
case n > 0:
for ; n > 0; n-- {
r = r.next
}
}
return r
}
// New creates a ring of n elements.
//read note 创建n个节点的环
func New1(n int) *Ring {
if n <= 0 {
return nil
}
r := new(Ring)
p := r
for i := 1; i < n; i++ {
p.next = &Ring{prev: p}
p = p.next
}
p.next = r
r.prev = p
return r
}
// Link connects ring r with ring s such that r.Next()
// becomes s and returns the original value for r.Next().
// r must not be empty.
//
// If r and s point to the same ring, linking
// them removes the elements between r and s from the ring.
// The removed elements form a subring and the result is a
// reference to that subring (if no elements were removed,
// the result is still the original value for r.Next(),
// and not nil).
//
// If r and s point to different rings, linking
// them creates a single ring with the elements of s inserted
// after r. The result points to the element following the
// last element of s after insertion.
//
//read note 链接环,如果是两个相同的环则环不改变,链接完环会少掉原来的第一个元素....(神奇)
// 如果是两个不同的环,则把另一个环接到上一个环的后面,链接完的第一个元素是原来环的next的元素.第二个元素
func (r *Ring) Link(s *Ring) *Ring {
n := r.Next()
if s != nil {
p := s.Prev()
// Note: Cannot use multiple assignment because
// evaluation order of LHS is not specified.
r.next = s
s.prev = r
n.prev = p
p.next = n
}
return n
}
// Unlink removes n % r.Len() elements from the ring r, starting
// at r.Next(). If n % r.Len() == 0, r remains unchanged.
// The result is the removed subring. r must not be empty.
//
//read note 断开环上n个元素,这里会根据n%r.Len 得到的余数进行Unlink,因为环是没有起点终点的,所以超过或者不超过环的长度都是按照余数进行处理
func (r *Ring) Unlink(n int) *Ring {
if n <= 0 {
return nil
}
return r.Link(r.Move(n + 1))
}
// Len computes the number of elements in ring r.
// It executes in time proportional to the number of elements.
//
func (r *Ring) Len() int {
n := 0
if r != nil {
n = 1
for p := r.Next(); p != r; p = p.next {
n++
}
}
return n
}
// Do calls function f on each element of the ring, in forward order.
// The behavior of Do is undefined if f changes *r.
//read note 对环上的所有元素进行函数操作,但是这边的操作好像是没办法改变环中的元素的,只能进行提取或者输出
func (r *Ring) Do(f func(interface{})) {
if r != nil {
f(r.Value)
for p := r.Next(); p != r; p = p.next {
f(p.Value)
}
}
}
+36
View File
@@ -0,0 +1,36 @@
/*
* @Author : huangzj
* @Time : 2020/12/2 15:39
* @Description
*/
package testHeap
type Person struct {
Name string //名字
Age int //年龄
Money float64 //身价
}
type heapTool []*Person
func (h *heapTool) Less(i, j int) bool {
return (*h)[i].Age < (*h)[j].Age
}
func (h *heapTool) Swap(i, j int) {
(*h)[i], (*h)[j] = (*h)[j], (*h)[i]
}
func (h *heapTool) Len() int {
return len(*h)
}
func (h *heapTool) Pop() (v interface{}) {
*h, v = (*h)[:h.Len()-1], (*h)[h.Len()-1]
return
}
func (h *heapTool) Push(v interface{}) {
*h = append(*h, v.(*Person))
}
+62
View File
@@ -0,0 +1,62 @@
/*
* @Author : huangzj
* @Time : 2020/12/2 11:19
* @Description
*/
package testHeap
import (
"container/heap"
"fmt"
"testing"
)
func TestHeapTool(t *testing.T) {
personList := new(heapTool)
personList.Push(&Person{
Name: "小明",
Age: 20,
Money: 100000.99,
})
personList.Push(&Person{
Name: "小施",
Age: 30,
Money: 1002341.99,
})
personList.Push(&Person{
Name: "小康",
Age: 10,
Money: 200.99,
})
personList.Push(&Person{
Name: "老施",
Age: 50,
Money: 10343240000.99,
})
personList.Push(&Person{
Name: "老康",
Age: 70,
Money: 10340.99,
})
personList.Push(&Person{
Name: "老明",
Age: 80,
Money: 13240000.99,
})
personList.Push(&Person{
Name: "老林",
Age: 90,
Money: 10340000.99,
})
heap.Init(personList)
for personList.Len() > 0 {
pop := heap.Pop(personList)
fmt.Println(fmt.Sprintf("%v,%v岁,资产:%v", pop.(*Person).Name, pop.(*Person).Age, pop.(*Person).Money))
}
}
+69
View File
@@ -0,0 +1,69 @@
/*
* @Author : huangzj
* @Time : 2020/12/3 21:58
* @Description:测试list.go包的元素
*/
package testHeap
import (
"container/list"
"fmt"
"testing"
)
func TestList(t *testing.T) {
list2 := list.New()
list2.PushFront(Person{
Name: "康康",
Age: 10,
Money: 20,
})
list2.PushBack(Person{
Name: "老施",
Age: 40,
Money: 1000000,
})
for e := list2.Front(); e != nil; e = e.Next() {
value := e.Value.(Person)
fmt.Println(fmt.Sprintf("名字:%v,年龄:%v,身家:%v", value.Name, value.Age, value.Money))
}
fmt.Println()
fmt.Println()
frontE := list2.Front()
list2.MoveToBack(frontE)
for e := list2.Front(); e != nil; e = e.Next() {
value := e.Value.(Person)
fmt.Println(fmt.Sprintf("名字:%v,年龄:%v,身家:%v", value.Name, value.Age, value.Money))
}
fmt.Println()
fmt.Println()
xiaozhang := list2.InsertBefore(Person{
Name: "小张",
Age: 10,
Money: 50,
}, list2.Front())
for e := list2.Front(); e != nil; e = e.Next() {
value := e.Value.(Person)
fmt.Println(fmt.Sprintf("名字:%v,年龄:%v,身家:%v", value.Name, value.Age, value.Money))
}
fmt.Println()
fmt.Println()
list2.Remove(xiaozhang)
for e := list2.Front(); e != nil; e = e.Next() {
value := e.Value.(Person)
fmt.Println(fmt.Sprintf("名字:%v,年龄:%v,身家:%v", value.Name, value.Age, value.Money))
}
fmt.Println()
fmt.Println()
front := list2.Front().Value.(Person)
fmt.Println(fmt.Sprintf("名字:%v,年龄:%v,身家:%v", front.Name, front.Age, front.Money))
}
+114
View File
@@ -0,0 +1,114 @@
/*
* @Author : huangzj
* @Time : 2020/12/7 9:33
* @Description
*/
package testHeap
import (
"container/ring"
"fmt"
"testing"
)
func TestRing(t *testing.T) {
fmt.Println("测试空链表")
var rings ring.Ring
fmt.Println(rings.Next().Value)
fmt.Println("")
fmt.Println("")
fmt.Println("测试环")
newRing := makeN(10)
Print(newRing)
fmt.Println("")
fmt.Println("")
fmt.Println("测试环Link自己")
newRing = makeN(10)
newRing = newRing.Link(newRing)
Print(newRing)
fmt.Println()
fmt.Println()
fmt.Println("测试环Link其他环")
newRing = makeN(10)
newRing1 := makeN(5)
newRing = newRing.Link(newRing1)
Print(newRing)
fmt.Println()
fmt.Println()
fmt.Println("测试Move")
newRing1 = makeN(5)
newRing1 = newRing1.Move(3)
Print(newRing1)
fmt.Println()
fmt.Println()
fmt.Println("测试Do,没有办法改变环中的元素.")
newRing1 = makeN(5)
newRing1.Do(func(i interface{}) {
i = i.(int) + 1000
})
Print(newRing1)
newRingx := ring.New(3)
for i := 1; i <= newRingx.Len(); i++ {
newRingx.Value = Person{
Name: "小明",
Age: 100,
Money: 19999,
}
newRingx = newRingx.Next()
newRingx.Value = Person{
Name: "小康",
Age: 50,
Money: 19921999,
}
newRingx = newRingx.Next()
newRingx.Value = Person{
Name: "小施",
Age: 20,
Money: 1111999,
}
}
fmt.Println("测试Do,只能对元素进行提取或者输出.")
s := make([]int, 0)
newRingx.Do(func(i interface{}) {
s = append(s, i.(Person).Age)
})
for _, item := range s {
fmt.Println(item)
}
fmt.Println()
fmt.Println()
fmt.Println("测试Unlink")
newRing1 = makeN(5)
newRing2 := newRing1.Unlink(2)
Print(newRing1)
println()
fmt.Println("如果用赋值语句,可以返回被移除的元素")
Print(newRing2)
}
func Print(r *ring.Ring) {
i, n := 0, r.Len()
for p := r; i < n; p = p.Next() {
fmt.Println(fmt.Sprintf("当前元素是%v", p.Value))
i++
}
}
//创造对应的链表
func makeN(n int) *ring.Ring {
r := ring.New(n)
for i := 1; i <= n; i++ {
r.Value = i
r = r.Next()
}
return r
}