LRU Cache(go)

本文详细介绍了一种使用双向链表和map结构实现的LRU(Least Recently Used)缓存算法。通过具体代码展示了如何构造LRU缓存,包括插入、获取和移除元素的操作流程,确保缓存遵循最近最少使用原则。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实现方法:采用双向链表和map结构进行实现

代码如下:

type Node struct {
	key   int
	value int
	next  *Node
	pre   *Node
}

type LRUCache struct {
	capacity int
	count    int
	head     *Node
	tail     *Node
	hash     map[int]*Node
}

func ConstructorLRU(capacity int) LRUCache {
	return LRUCache{capacity: capacity, hash: make(map[int]*Node)}
}

func (this *LRUCache) Get(key int) int {
	nd, ok := this.hash[key]
	if ok {
		if nd.pre == nil && nd.next == nil {
			this.head = nil
			this.tail = nil
		} else if nd.pre == nil && nd.next != nil {
			this.head = nd.next
			this.head.pre = nil
		} else if nd.pre != nil && nd.next == nil {
			this.tail = nd.pre
			this.tail.next = nil
		} else {
			nd.next.pre = nd.pre
			nd.pre.next = nd.next
		}
		this.count --
		this.insertIntoHead(nd)
		return nd.value
	}
	return -1
}


func (this *LRUCache) Put(key int, value int)  {
	nd, ok := this.hash[key]
	tempNode := &Node{key:key, value:value}
	if ok {
		nd.value = value
		tempNode = nd
		if nd.pre == nil && nd.next == nil {  // 当前链表中只有一个节点
			this.head = nil
			this.tail = nil
		} else if nd.pre == nil && nd.next != nil { // 插入的节点在链表中,且是头节点
			this.head = nd.next
			this.head.pre = nil
		} else if nd.pre != nil && nd.next == nil { // 插入的节点在链表中,且是尾节点
			this.tail = nd.pre
			this.tail.next = nil
		} else {
			nd.next.pre = nd.pre
			nd.pre.next = nd.next
		}
		this.count --
	}
	this.insertIntoHead(tempNode)
	if this.count > this.capacity {
		this.removeFromTail()
	}
}

// 向链表中插入头节点
func (this *LRUCache) insertIntoHead(node *Node) {
	if nil == this.head {
		node.pre = nil
		node.next = nil
		this.head = node
		this.tail = node
	} else {
		this.head.pre = node
		node.next = this.head
		node.pre = nil
		this.head = node
	}
	this.hash[node.key] = node
	this.count ++
}

// 删除链表中的尾节点
func (this *LRUCache) removeFromTail() {
	if nil == this.tail || nil == this.tail.pre {
		this.head = nil
		this.tail = nil
	} else {
		delete(this.hash, this.tail.key)
		this.tail = this.tail.pre
		this.tail.next = nil
	}
	this.count --
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值