LRU算法

golang实现,比较简单的版本

package lru

import "container/list"

type Node struct {
    K, V interface{}
}

type LRU struct {
    list *list.List
    cacheMap map[interface{}]*list.Element
    Size int
}

func NewLRU(cap int) *LRU {
    return &LRU{
        Size: cap,
        list: list.New(),
        cacheMap: make(map[interface{}]*list.Element, cap),
    }
}

func (lru *LRU) Get(k interface{}) (v interface{}, ret bool) {
    if ele, ok := lru.cacheMap[k]; ok {
        lru.list.MoveToFront(ele)
        return ele.Value.(*Node).V, true
    }

    return nil, false
}

func (lru *LRU) Set(k, v interface{}) {
    if ele, ok := lru.cacheMap[k]; ok {
        lru.list.MoveToFront(ele)
        ele.Value.(*Node).V = v
        return
    }

    if lru.list.Len() == lru.Size {
        last := lru.list.Back()
        node := last.Value.(*Node)
        delete(lru.cacheMap, node.K)
        lru.list.Remove(last)
    }

    ele := lru.list.PushFront(&Node{k, v})
    lru.cacheMap[k] = ele
}

 

end

 

posted @ 2020-06-30 11:17  zhangyu63  阅读(121)  评论(0编辑  收藏  举报