1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
| type Node struct { Key int Value int Next *Node Pre *Node }
type LRUCache struct { Cap int Size int NodeMap map[int]*Node Head *Node Tail *Node }
func Constructor(capacity int) LRUCache { lru := LRUCache{ Cap: capacity, Size: 0, } lru.NodeMap = make(map[int]*Node, 0) lru.Tail = &Node{} lru.Head = &Node{}
return lru }
func (this *LRUCache) moveToHead(node *Node) { if this.Size == 0 { this.Head.Next = node node.Pre = this.Head this.Tail.Pre = node node.Next = this.Tail return }
node.Next = this.Head.Next this.Head.Next.Pre = node node.Pre = this.Head this.Head.Next = node }
func (this *LRUCache) delNode(node *Node) { node.Pre.Next = node.Next node.Next.Pre = node.Pre }
func (this *LRUCache) Get(key int) int { node, ok := this.NodeMap[key] if !ok { return -1 }
this.delNode(node)
this.moveToHead(node)
return node.Value }
func (this *LRUCache) Put(key int, value int) { existNode, ok := this.NodeMap[key] if ok { existNode.Value = value
this.delNode(existNode) this.moveToHead(existNode)
return }
node := &Node{ Key: key, Value: value, } this.NodeMap[key] = node
if this.Size < this.Cap { this.moveToHead(node) this.Size++ } else { this.moveToHead(node)
nowTailPre := this.Tail.Pre this.delNode(nowTailPre) delete(this.NodeMap, nowTailPre.Key) } }
|