★container | heap堆操作, list雙向鏈表,ring環(huán)形鏈表
現(xiàn)在網(wǎng)上的算法題揍鸟,很少有可以用golang作答的运杭,不過看看別人造的輪子還是挺有意思的
container本身并不是包患久,但目錄下包括三個子包:heap,list茅姜,ring
heap
- 包含一個Interface接口奏夫,接口定義了Push(x interface{}),Pop() interface{} 打瘪,并包含了sort.Interface接口友鼻。
- 這里的堆是小頂堆
- heap并沒有可用的實現(xiàn),但在test中找到一個:
// An IntHeap is a min-heap of ints.
type IntHeap []int
func (h IntHeap) Len() int { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *IntHeap) Push(x interface{}) {
// Push and Pop use pointer receivers because they modify the slice's length,
// not just its contents.
*h = append(*h, x.(int))
}
func (h *IntHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[0 : n-1]
return x
}
- 在進行heap.Pop闺骚,heap.Remove彩扔,heap.Push時,會自動fix為小頂堆
PS:所以堆拍啥的只要pop() pop() pop()就可以了
list ring
這倆一個尿性放一塊看了
list是有頭的所以有type List struct
和 type Element struct
僻爽,Element是雙向的并且有*List指針
ring是一個固定大小的環(huán)虫碉,僅由type Ring struct
組成