go语言实现LRU算法

go语言实现LRU算法

go语言实现LRU算法

package main


import (
	"container/list"
	"errors"
	"fmt"
	"sync"
)

type Lru struct {
	max   int
	l     *list.List
	Call  func(key interface{}, value interface{})
	cache map[interface{}]*list.Element
	mu    *sync.Mutex
}

type Node struct {
	Key interface{}
	Val interface{}
}

func NewLru(len int) *Lru {
	return &Lru{
		max:   len,
		l:     list.New(),
		cache: make(map[interface{}]*list.Element),
		mu:    new(sync.Mutex),
	}
}

func (l *Lru) Add(key interface{}, val interface{}) error {
	if l.l == nil {
		return errors.New("not init NewLru")
	}
	l.mu.Lock()
	defer l.mu.Unlock()
	if e, ok := l.cache[key]; ok { //以及存在
		e.Value.(*Node).Val = val
		l.l.MoveToFront(e)
		return nil
	}
	ele := l.l.PushFront(&Node{
		Key: key,
		Val: val,
	})
	l.cache[key] = ele
	if l.max != 0 && l.l.Len() > l.max {
		if e := l.l.Back(); e != nil {
			l.l.Remove(e)
			node := e.Value.(*Node)
			delete(l.cache, node.Key)
			if l.Call != nil {
				l.Call(node.Key, node.Val)
			}
		}
	}
	return nil
}

func (l *Lru) Get(key interface{}) (val interface{}, ok bool) {
	if l.cache == nil {
		return
	}
	l.mu.Lock()
	defer l.mu.Unlock()
	if ele, ok := l.cache[key]; ok {
		l.l.MoveToFront(ele)
		return ele.Value.(*Node).Val, true
	}
	return
}

func (l *Lru) GetAll() []*Node {
	l.mu.Lock()
	defer l.mu.Unlock()
	var data []*Node
	for _, v := range l.cache {
		data = append(data, v.Value.(*Node))
	}
	return data
}

func (l *Lru) Del(key interface{}) {
	if l.cache == nil {
		return
	}
	l.mu.Lock()
	defer l.mu.Unlock()
	if ele, ok := l.cache[key]; ok {
		delete(l.cache, ele)
		if e := l.l.Back(); e != nil {
			l.l.Remove(e)
			delete(l.cache, key)
			if l.Call != nil {
				node := e.Value.(*Node)
				l.Call(node.Key, node.Val)
			}
		}
	}

}

func main() {
	lru := NewLru(3)
	err1 := lru.Add(1,"用户1")
	if err1 != nil{}
	//fmt.Println(lru.l)
	err2 := lru.Add(2,"用户2")
	if err2 != nil{}
	//fmt.Println(lru.l)
	err3 := lru.Add(3,"用户3")
	if err3 != nil{}
	//fmt.Println(lru.l)
	err4 := lru.Add(4,"用户4")
	if err4 != nil{}
	//fmt.Println(lru.l)
	//if _,ok := lru.Get(1);ok{}
	//if _,ok := lru.Get(2);ok{}
	//if _,ok := lru.Get(1);ok{}
	lru.Get(1)
	err5 := lru.Add(5,"用户5")
	err6 := lru.Add(3,"用户300")
	if err6 == nil{}
	if err5 != nil{}
	//fmt.Println(lru.l)
	x := lru.GetAll()
	for _,i := range x{fmt.Println(*i)}
	//fmt.Println(lru.l)
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值