SoFunction
Updated on 2025-03-05

Golang implements the LRU cache elimination algorithm sample code

LRU cache elimination algorithm

LRU is the abbreviation of the least recently used strategy. It eliminates data based on the historical access records of the data. Its core idea is "If the data has been accessed recently, the chance of being accessed in the future will be higher."

Two-way linked list implements LRU

All the cache positions are connected with a double-linked list. When a position is accessed (get/put), adjust the direction of the linked list and adjust the position to the position of the linked list header, and the newly added cache is directly added to the linked list header.

In this way, after multiple operations, the recently accessed (get/put) will be moved towards the head of the linked list, and the unaccessible will be moved behind the linked list, and the end of the linked list indicates the least recently used cache.

When the cache capacity upper limit is reached, the last position of the linked list is the least visited cache. We only need to delete the last cache of the linked list to continue adding the new cache.

Code implementation

type Node struct {
  Key int
  Value int
  pre *Node
  next *Node
}

type LRUCache struct {
  limit int
  HashMap map[int]*Node
  head *Node
  end *Node
}

func Constructor(capacity int) LRUCache{
  lruCache := LRUCache{limit:capacity}
   = make(map[int]*Node, capacity)
  return lruCache
}

func (l *LRUCache) Get(key int) int {
  if v,ok:= [key];ok {
    (v)
    return 
  }else {
    return -1
  }
}

func (l *LRUCache) Put(key int, value int) {
  if v,ok := [key];!ok{
    if len() >= {
      oldKey := ()
      delete(, oldKey)
    }
    node := Node{Key:key, Value:value}
    (&node)
    [key] = &node
  }else {
     = value
    (v)
  }
}

func (l *LRUCache) refreshNode(node *Node){
  if node ==  {
    return
  }
  (node)
  (node)
}

func (l *LRUCache) removeNode(node *Node) int{
  if node ==  {
     = 
  }else if node ==  {
     = 
  }else {
     = 
     = 
  }
  return 
}

func (l *LRUCache) addNode(node *Node){
  if  != nil {
     = node
     = 
     = nil
  }
   = node
  if  == nil {
     = node
  }
}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.