package main
import "fmt"
* Your LRUCache object will be instantiated and called as such:
* obj := Constructor(capacity);
* param_1 := obj.Get(key);
* obj.Put(key,value);
*/
func main() {
capacity := 2
obj := Constructor(capacity)
obj.Put(2, 1)
obj.Put(2, 2)
fmt.Println(obj.Get(2))
obj.Put(1, 1)
obj.Put(4, 1)
fmt.Println(obj.Get(2))
}
type LinkNode struct {
key, val int
next, pre *LinkNode
}
type LRUCache struct {
searchMap map[int]*LinkNode
cap int
head, tail *LinkNode
}
func Constructor(capacity int) LRUCache {
head := &LinkNode{0, 0, nil, nil}
tail := &LinkNode{0, 0, nil, nil}
head.pre = tail
tail.next = head
return LRUCache{make(map[int]*LinkNode, 0), capacity, head, tail}
}
func (this *LRUCache) Get(key int) int {
node, exist := this.searchMap[key]
if exist {
this.moveToHead(node)
return node.val
}
return -1
}
func (this *LRUCache) Put(key int, value int) {
node, exist := this.searchMap[key]
if exist {
node.val = value
this.moveToHead(node)
} else {
newNode := &LinkNode{key, value, nil, nil}
if len(this.searchMap) == this.cap {
delete(this.searchMap, this.tail.next.key)
this.removeNode(this.tail.next)
}
this.addNode(newNode)
this.searchMap[key] = newNode
}
}
func (this *LRUCache) moveToHead(node *LinkNode) {
this.removeNode(node)
this.addNode(node)
}
func (this *LRUCache) addNode(node *LinkNode) {
head := this.head
node.next = head
node.pre = head.pre
head.pre.next = node
head.pre = node
}
func (this *LRUCache) removeNode(node *LinkNode) {
node.pre.next = node.next
node.next.pre = node.pre
}
评论