版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yjw19901214/article/details/83624216
实现方法:采用双向链表和map结构进行实现
代码如下:
type Node struct {
key int
value int
next *Node
pre *Node
}
type LRUCache struct {
capacity int
count int
head *Node
tail *Node
hash map[int]*Node
}
func ConstructorLRU(capacity int) LRUCache {
return LRUCache{capacity: capacity, hash: make(map[int]*Node)}
}
func (this *LRUCache) Get(key int) int {
nd, ok := this.hash[key]
if ok {
if nd.pre == nil && nd.next == nil {
this.head = nil
this.tail = nil
} else if nd.pre == nil && nd.next != nil {
this.head = nd.next
this.head.pre = nil
} else if nd.pre != nil && nd.next == nil {
this.tail = nd.pre
this.tail.next = nil
} else {
nd.next.pre = nd.pre
nd.pre.next = nd.next
}
this.count --
this.insertIntoHead(nd)
return nd.value
}
return -1
}
func (this *LRUCache) Put(key int, value int) {
nd, ok := this.hash[key]
tempNode := &Node{key:key, value:value}
if ok {
nd.value = value
tempNode = nd
if nd.pre == nil && nd.next == nil { // 当前链表中只有一个节点
this.head = nil
this.tail = nil
} else if nd.pre == nil && nd.next != nil { // 插入的节点在链表中,且是头节点
this.head = nd.next
this.head.pre = nil
} else if nd.pre != nil && nd.next == nil { // 插入的节点在链表中,且是尾节点
this.tail = nd.pre
this.tail.next = nil
} else {
nd.next.pre = nd.pre
nd.pre.next = nd.next
}
this.count --
}
this.insertIntoHead(tempNode)
if this.count > this.capacity {
this.removeFromTail()
}
}
// 向链表中插入头节点
func (this *LRUCache) insertIntoHead(node *Node) {
if nil == this.head {
node.pre = nil
node.next = nil
this.head = node
this.tail = node
} else {
this.head.pre = node
node.next = this.head
node.pre = nil
this.head = node
}
this.hash[node.key] = node
this.count ++
}
// 删除链表中的尾节点
func (this *LRUCache) removeFromTail() {
if nil == this.tail || nil == this.tail.pre {
this.head = nil
this.tail = nil
} else {
delete(this.hash, this.tail.key)
this.tail = this.tail.pre
this.tail.next = nil
}
this.count --
}