container
heap
import ("container/heap""fmt")// An IntHeap is a min-heap of ints.type IntHeap []intfunc (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{}) {*h = append(*h, x.(int))}// 末尾删除元素func (h *IntHeap) Pop() interface{} {old := *hn := len(old)x := old[n-1]*h = old[0 : n-1]return x}func main() {h := &IntHeap{2, 1, 5}heap.Init(h)heap.Push(h, 3)fmt.Printf("minimum: %d\n", (*h)[0]) // 小根堆for h.Len() > 0 {fmt.Printf("%d ", heap.Pop(h))}}
list
import ("container/list""fmt")func main() {// 创建一个新的链表l := list.New()e2 := l.PushBack(2)e5 := l.PushBack(5)l.InsertBefore(3, e2)l.InsertAfter(19, e5)for e := l.Front(); e != nil; e = e.Next() {fmt.Println(e.Value)}}
list 构建 queue/stack
// queuequeue := list.New()// queue pushqueue.pushBack()// queue popfront := queue.Front()queue.Remove(front)// stackstack := list.New()// stack pushstack.pushBack()// stack popback := stack.Back()stack.Remove(back)
由于 stack 是在一端进行增加删除,所以使用切片来模拟 stack 会更加方便。
// stackstack := []int{}// stack pushstack = append(stack, elm)// stack popstack = stack[:len(stack)-1]
LRU
package lrutype LRU struct {cap intpos map[int]*Elementroot Element // root.next = first, root.pre = last}// Element a list elementtype Element struct {Value intnext, pre *Element}// New returns an initialized listfunc New(cap int) *LRU {return new(LRU).Init(cap)}// Init initializes the lru listfunc (lru *LRU) Init(cap int) *LRU {lru.root.next = &lru.rootlru.root.pre = &lru.rootlru.cap = caplru.pos = make(map[int]*Element)return lru}// Query visit a valuefunc (lru *LRU) Query(v int) {if lru.pos[v] != nil {lru.toLast(lru.pos[v])} else {if len(lru.pos) == lru.cap {lru.pop()}lru.push(v)}}func (lru *LRU) toLast(elm *Element) {elmPre, elmNext := elm.pre, elm.nextelmPre.next = elmNextelmNext.pre = elmPrecurLast := lru.root.precurLast.next = elmelm.pre = curLastelm.next = &lru.rootlru.root.pre = elm}// remove least visit element, which is the head of the listfunc (lru *LRU) pop() int {head := lru.root.nextlru.root.next = head.nexthead.next.pre = &lru.rootdelete(lru.pos, head.Value)return head.Value}func (lru *LRU) push(v int) {elm := &Element{Value: v,}curLast := lru.root.precurLast.next = elmlru.root.pre = elmelm.next = &lru.rootelm.pre = curLastlru.pos[v] = elm}
