用Go语言帮我写一个LRU缓存
时间: 2023-03-31 16:00:44 浏览: 83
好的,我可以为您编写一个LRU缓存的Go语言实现。以下是代码示例:
```go
package main
import (
"container/list"
"fmt"
)
type LRUCache struct {
capacity int
cache map[int]*list.Element
list *list.List
}
type entry struct {
key int
value int
}
func Constructor(capacity int) LRUCache {
return LRUCache{
capacity: capacity,
cache: make(map[int]*list.Element),
list: list.New(),
}
}
func (this *LRUCache) Get(key int) int {
if elem, ok := this.cache[key]; ok {
this.list.MoveToFront(elem)
return elem.Value.(*entry).value
}
return -1
}
func (this *LRUCache) Put(key int, value int) {
if elem, ok := this.cache[key]; ok {
elem.Value.(*entry).value = value
this.list.MoveToFront(elem)
} else {
if this.list.Len() == this.capacity {
tail := this.list.Back()
delete(this.cache, tail.Value.(*entry).key)
this.list.Remove(tail)
}
elem := this.list.PushFront(&entry{key, value})
this.cache[key] = elem
}
}
func main() {
cache := Constructor(2)
cache.Put(1, 1)
cache.Put(2, 2)
fmt.Println(cache.Get(1)) // 1
cache.Put(3, 3)
fmt.Println(cache.Get(2)) // -1
cache.Put(4, 4)
fmt.Println(cache.Get(1)) // -1
fmt.Println(cache.Get(3)) // 3
fmt.Println(cache.Get(4)) // 4
}
```
以上是一个简单的LRU缓存实现,您可以根据需要进行修改和扩展。
阅读全文