运行
格式化
停止
分享
赞助
package main import ( "fmt" "math/rand" "sync" ) // 链表 type LinkItem struct { Pre *LinkItem Next *LinkItem Num float32 } func (l *LinkItem) String() string { return fmt.Sprintf("%.2f", l.Num) } func (l *LinkItem) PrintAll() { if l.Pre == nil { fmt.Printf("[") } fmt.Printf("%v ", l) if l.Next == nil { fmt.Printf("]\n") } else { l.Next.PrintAll() } } func NewHolder(length int) *Holder { h := &Holder{} h.length = length h.holder = make([]*LinkItem, length) var preItem *LinkItem for i := 0; i < length; i++ { linkItem := &LinkItem{} if preItem != nil { preItem.Next = linkItem linkItem.Pre = preItem } h.holder[i] = linkItem preItem = linkItem } h.maxItem = h.holder[0] h.minItem = h.holder[length-1] return h } // 保存数据容器 type Holder struct { lock sync.RWMutex // 当前位置 current int length int // 数值保持者 holder []*LinkItem maxItem *LinkItem minItem *LinkItem } // 把数放到holder func (h *Holder) Push(num float32) { h.lock.Lock() defer h.lock.Unlock() currentItem := h.holder[h.current] currentItem.Num = num // 截断该Item preItem := currentItem.Pre nextItem := currentItem.Next if preItem == nil { h.maxItem = nextItem nextItem.Pre = nil } else if nextItem == nil { h.minItem = preItem preItem.Next = nil } else { preItem.Next = nextItem nextItem.Pre = preItem } // 重新排序 curremtItem (该处根据需要重新定义排须规则) handleItem := h.maxItem for { if handleItem.Num <= currentItem.Num { if handleItem.Pre == nil { // currentItem 是最大 handleItem.Pre = currentItem currentItem.Pre = nil currentItem.Next = handleItem h.maxItem = currentItem } else { handleItem.Pre.Next = currentItem currentItem.Pre = handleItem.Pre handleItem.Pre = currentItem currentItem.Next = handleItem } break } else { if handleItem.Next == nil { // currentItem 是最小 handleItem.Next = currentItem currentItem.Next = nil h.minItem = currentItem break } else { handleItem = handleItem.Next } } } h.current = h.current + 1 h.current = h.current % h.length } // 最大值 func (h *Holder) Max() float32 { h.lock.RLock() defer h.lock.RUnlock() return h.maxItem.Num } // 最小值 func (h *Holder) Min() float32 { h.lock.RLock() defer h.lock.RUnlock() return h.minItem.Num } func main() { h := NewHolder(10) for i := 0; i < 32; i++ { h.Push(float32(rand.Intn(100))) } fmt.Println(h.holder) h.maxItem.PrintAll() fmt.Printf("max is %.2f min is %.2f\n", h.Max(), h.Min()) }