type LRUCache struct {
size int
capacity int
cache map[int]*DLinkedNode
head, tail *DLinkedNode
}
type DLinkedNode struct {
key, val int
prev, next *DLinkedNode
}
func initDLinkedNode(key, val int) *DLinkedNode {
return &DLinkedNode{
key: key,
val: val,
}
}
func Constructor(capacity int) LRUCache {
l := LRUCache{
cache: map[int]*DLinkedNode{},
head: initDLinkedNode(0, 0),
tail: initDLinkedNode(0, 0),
capacity: capacity,
}
l.head.next = l.tail
l.tail.prev = l.head
return l
}
func (this *LRUCache) addToHead(node *DLinkedNode) {
node.prev = this.head
node.next = this.head.next
this.head.next.prev = node
this.head.next = node
}
func (this *LRUCache) removeNode(node *DLinkedNode) {
// 将节点从链表中单独抽出来
node.prev.next = node.next
node.next.prev = node.prev
}
func (this *LRUCache) moveToHead(node *DLinkedNode) {
this.removeNode(node)
this.addToHead(node)
}
func (this *LRUCache) removeTail() *DLinkedNode {
node := this.tail.prev
this.removeNode(node)
delete(this.cache, node.key)
return node
}
// 通过cache的map关系,找到对应的值,该值存储在node的val属性中。
func (this *LRUCache) Get(key int) int {
// 如果key是不存在的,那就返回-1
if _, ok := this.cache[key]; !ok {
return -1
}
node := this.cache[key]
this.moveToHead(node)
return node.val
}
func (this *LRUCache) Put(key int, val int) {
if _, ok := this.cache[key]; !ok {
node := initDLinkedNode(key, val)
this.cache[key] = node
this.addToHead(node)
this.size++
if this.size > this.capacity {
removed := this.removeTail()
delete(this.cache, removed.key)
this.size--
}
} else {
node := this.cache[key]
node.val = val
this.moveToHead(node)
}
}