

Go 语言需要自己创建双向链表,推荐创建2个哨兵节点
package mainimport "fmt"type Node struct {key intvalue intpre *Nodenext *Node}type LRUCache struct {m map[int] *Nodehead *Nodetail *Nodecapacity int}func Constructor(capacity int) LRUCache {cache := LRUCache{m: make(map[int]*Node),head: &Node{},tail: &Node{},capacity: capacity,}cache.head.next = cache.tailcache.tail.pre = cache.headreturn cache}// 头部添加元素func (this *LRUCache)AddHead(n *Node){tmp := this.head.nextthis.head.next = nn.next = tmpn.pre = this.headtmp.pre = n}func (this *LRUCache)RemoveNode(n *Node){pre := n.prenext := n.nextpre.next = nextnext.pre = pren.pre = niln.next = nil}func (this *LRUCache) Get(key int) int {node ,ok:= this.m[key]if ok {this.RemoveNode(node)this.AddHead(node)return node.value}return -1}func (this *LRUCache) Put(key int, value int) {node ,ok:= this.m[key]if ok {// 存在if node.value!= value {node.value = value}this.RemoveNode(node)this.AddHead(node)}else {n := &Node{key:key,value: value,}if this.capacity==len(this.m) {// 删除delete(this.m,this.tail.pre.key)this.RemoveNode(this.tail.pre)}this.AddHead(n)this.m[key] = n}}func main() {cache := Constructor(2)cache.Put(1,1)cache.Put(2,2)fmt.Println(cache.Get(1))//1cache.Put(3,3)fmt.Println(cache.Get(2))//-1cache.Put(4,4)fmt.Println(cache.Get(1))//-1fmt.Println(cache.Get(3))//3fmt.Println(cache.Get(4))//4}
