用Go语言帮我写一个LRU缓存
时间: 2023-04-02 20:01:42 浏览: 102
好的,我可以为您编写一个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 {
this.list.MoveToFront(elem)
elem.Value.(*entry).value = value
} else {
if len(this.cache) == this.capacity {
last := this.list.Back()
delete(this.cache, last.Value.(*entry).key)
this.list.Remove(last)
}
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
}
```
以上是Go语言的LRU缓存实现,希望能对您有所帮助。
阅读全文