```go //缓存里的数据结构,k-v键值对 type entry struct{ key,value int }
//LRUCache结构,容量 //list.List是go包提供的双向链表,有PushFront、PushBack、MoveToFront、Remove、Front、Back等功能 //建立一个key-节点等哈希表 type LRUCache struct { capacity int list *list.List keyToNode map[int]*list.Element }
//取出,就用哈希表来查看,并且因为这算一个操作 //把这个节点放到最前面 //因为list本身每个Element都是interface{},所以需要.(entry)类型断言 func (this *LRUCache) Get(key int) int { node:=this.keyToNode[key] if node==nil{ return -1 } this.list.MoveToFront(node) return node.Value.(entry).value }
func (this *LRUCache) Put(key int, value int) { //如果关键字存在,就变更value if node:=this.keyToNode[key];node!=nil{ node.Value=entry{key,value} this.list.MoveToFront(node) return } //如果不存在,就在最前面插入k-v this.keyToNode[key]=this.list.PushFront(entry{key,value}) //如果长度超出容量,就删掉结尾的k-v if len(this.keyToNode)>this.capacity{ delete(this.keyToNode,this.list.Remove(this.list.Back()).(entry).key) } }
/** * Your LRUCache object will be instantiated and called as such: * obj := Constructor(capacity); * param_1 := obj.Get(key); * obj.Put(key,value); */