Longest unused algorithm (LRU, Least recently used):
The LRU method is based on the use of each block, always select the longest time unused block replacement. This method is better to reflect the law of program locality.
Type cache struct {
M map[string]string//Storage k-v Nodem Map[string]*Node //Store k corresponds to the position of the nodes in the linked list L sizeintL*LinkedList//Doubly linked list, the longer it is used, the longer it is in front}type node struct {Keystring Pre*nodeNext *node}type linkedlist struct {head*node Rear*node}func newlinkedlist ()*LinkedList {return &linkedlist{}}
Doubly linked list Add node func (l*LinkedList)Add(n*node) { ifL.head==l.rear {l.head=N l.rear=n l.head.Next =N L.rear.pre=Nreturn} l.rear.Next =N N.pre=l.rear l.rear=N}
The doubly linked list removes the node func (l*LinkedList)Delete(n*node) {N.pre.Next =N.NextN.Next. Pre=N.pre}
The doubly linked list removes the head node func (l*linkedlist) Pop () string {Key:=L.head.KeyL.head=L.head.NextL.head.pre=Nilreturn Key}func (c*Cache) Init (sizeint) {C.M=Make (map[string]string, size) C.nodem=Make (map[string]*node, size) C.size=size C.L=newlinkedlist ()}
Func (c*Cache) Get (Keystring) (String, BOOL) {
1. No key existsif_, OK:=C.m[Key];!ok {return"", false}
2. There is a key to get the node pointer n n from Nodem:=C.nodem[Key]
Update linked list L
C.L.Delete(n) c.l.Add(N)
returnC.m[Key], False}func (c*CacheSet(Key, value string) {
1. This key already exists, replacing K-vif_, OK:=C.m[Key]; OK {n:=C.nodem[Key]C.L.Delete(n) c.l.Add(n) c.nodem[Key] =N c.m[Key] =valuereturn } //2. This key does not exist, if the cache capacity is full requiredElimination of the oldest keyif Len(C.M)>=c.size {popkey:=C.l.pop ()Delete(C.M, Popkey)Delete(C.nodem, Popkey)}//Add a new node NewNode:= &node{Key:Key} c.l.Add(newNode) c.m[Key] =value C.nodem[Key] =Newnode}func (c*Cache) Del (Keystring) { if_, OK:=C.m[Key];!ok {return} N:=C.nodem[Key]C.L.Delete(n)Delete(C.M,Key) Delete(C.nodem,Key)}
LRU Cache Implementation